java实现数组的冒泡排序、选择排序代码

数组排序之冒泡排序: 
相邻元素两两比较,大的往后放,第一次完毕,最大值出现在了最大索引处

package cn.lgt.sortarray;

public class MaoPaoSort {
    public static void maoPaoSort(int[] arr){
        //冒泡排序
        for(int i = 0; i < arr.length; i++){
            for(int j = 0; j < arr.length-1-i; j++){
                if(arr[j] > arr[j+1]){
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
            //PrintArray.printArray(arr);
        }
        PrintArray.printArray(arr);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

数组排序之选择排序: 
从0索引开始,依次和后面元素比较,小的往前放,第一次完毕,最小值出现在了最小索引处

package cn.lgt.sortarray;

public class XuanZeSort {
    //选择排序
    public static void xuanZeSort(int[] arr){
        for(int i = 0; i < arr.length; i++){
            for(int j = i+1; j< arr.length; j++){
                if(arr[i] > arr[j]){
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
            //PrintArray.printArray(arr);
        }
        PrintArray.printArray(arr);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

数组遍历输出

package cn.lgt.sortarray;

public class PrintArray {
    public static void printArray(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]);
            }
        }
        System.out.println("]");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

main方法代码

package cn.lgt.sortarray;

public class SortDemo {
    public static void main(String[] args) {
        System.out.println("排序算法");
        System.out.println("-----------------------");
        int[] array = {23, 2, 12, 33, 65, 46, 9, 1, 5};
        PrintArray.printArray(array);//输出数组
        //MaoPaoSort.maoPaoSort(array);//冒泡排序
        XuanZeSort.xuanZeSort(array);//选择排序
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40848783/article/details/80327891