栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

插入排序,冒泡排序,选择排序(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 
            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 
            for (int pre = end -1 ;pre >= 0 && arr[pre]>arr[pre+1];pre--)
            {
                swap(arr,pre,pre+1);
            }

        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/855152.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号