插入排序,冒泡排序,选择排序(Java版)

选择排序

  • 假设数组 int arr [] = {1, 5, 3, 6, 8, 7, 2, 3};
  • 如果下标为1的数比下标0的数小,则两个交换位置
  • 很显然,结束值为数组的长度,下标为数组长度减一
public static void selectSort(int[] arr) {
    //考虑边界值
    if (arr == null || arr.length < 2) {
        return;
    }
    int N = arr.length;
    for (int i = 0; i < N; i++) {
        int minIndex = i;
        for (int j = i + 1; j < N; j++) {
            minIndex = arr[j] < arr[minIndex] ? j : minIndex;
        }
        swap(arr, i, minIndex);
    }
}
  public static void swap(int[] arr, int i, int j) {
        int temp = arr[j];
        arr[j] = arr[i];
        arr[i] = temp;
    }
      public static void main(String[] args) {
        int[] a = {1, 5, 3, 6, 8, 7, 2, 3};
        printArr(a);
        selectSort(a);
//        bubbleSort(a);
//        insertSort(a);
//        insertSortPlus(a);
        printArr(a);
    }
      public static void printArr(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

冒泡排序

  • 假设数组 int arr [] = {1, 5, 3, 6, 8, 7, 2, 3};
  • 下标 0 1 1 2 2 3 3 4 4 5 … end-1 end
  • 如上进行两两比较,右边的比左边小则交换
public static void bubbleSort(int[] array) {
    if (array == null || array.length < 2) {
        return;
    }
    int N = array.length;
    for (int end = N-1; end >=0 ; end-- ) {
        // 0~end 的事
        for (int second = 1; second <=end ; second++) {
            if (array[second-1] > array[second]){
                swap(array,second-1,second);
            }
        }
    }

}

插入排序

  • 插入排序就是相当于你打扑克,假设你手里的牌是排序好的,新发的牌你要按顺序往里插入位置
public static void insertSort(int[] arr)
    {
        if (arr == null || arr.length < 2) {
            return;
        }
        // 0 0
        // 0 1
        // 0 2
        // 0 N
        int N = arr.length;
        for (int end = 1; end <N ; end++) {
            int currentNum = end;
            while (currentNum>=0 && arr[currentNum-1] > arr[currentNum]){
                // 交换
                swap(arr,currentNum-1,currentNum);
                currentNum--;
            }

        }
    }
 public static void insertSortPlus(int[] arr){
        if (arr == null || arr.length < 2) {
            return;
        }
        int N = arr.length;
        for (int end = 1; end <N ; end++) {
            for (int pre = end -1 ;pre >= 0 && arr[pre]>arr[pre+1];pre--)
            {
                swap(arr,pre,pre+1);
            }

        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值