- package 常见两种排序练习;
- public class ExerciseSort {
- public static void main(String[] args) {
- int [] arr = {100,89,200,67,5,-1,1000};
- selectSort(arr);
- printArr(arr);
- System.out.println();
- bubbleSort(arr);
- printArr(arr);
- }
- //冒泡排序法
- public static void bubbleSort(int [] arr)
- {
- for(int i = 0;i<arr.length-1;i++)
- {
- for(int j=0;j<arr.length-i-1;j++)
- {
- if(arr[j]>arr[j+1])
- {
- int temp = arr[j+1];
- arr[j+1] = arr[j];
- arr[j] = temp;
- }
- }
- }
- }
- //选择排序法
- public static void selectSort(int [] arr)
- {
- for(int i = 0;i<arr.length-1;i++)
- {
- for(int j=i+1;j<arr.length;j++)
- {
- if(arr[i]<arr[j])
- {
- int temp = arr[j];
- arr[j] = arr[i];
- arr[i] =temp;
- }
- }
- }
- }
- //打印数组
- public static void printArr(int [] arr)
- {
- System.out.print("{");
- for(int i=0;i<arr.length;i++)
- {
- if(i!=arr.length-1)
- {
- System.out.print(arr[i]+",");
- }
- else
- {
- System.out.print(arr[i]+"}");
- }
- }
- }
- }
复制代码
|
|