数据结构与算法

基础排序: 适用于数据量比较小的场景 

1.冒泡排序

       int arr[] = {6,4,3,5,1,2};
        for (int i = 0 ; i < arr.length ; i++){
            for (int j= 0 ; j < arr.length - 1 ; j++){
                if(arr[i] > arr[j]){
                    int k = arr[i];
                    arr[i] = arr[j];
                    arr[j] = k;
                }
            }
        }
        for (int i = arr.length - 1 ; i > 0 ; i--){
            for (int j = 0 ; j < i ; j++){

                if(arr[i] > arr[j]){
                    int k = arr[i];
                    arr[i] = arr[j];
                    arr[j] = k;
                }
            }
        }

  

2.选择排序

       int arr[] = {6,4,3,5,1,2};

        for (int i = 0 ; i < arr.length - 1 ; i ++){
            int mix = i;
            for (int j = i+1 ; j < arr.length ; j++){
                if(arr[mix] > arr[j]){
                    mix = j;
                }
            }
            int temp = arr[i];
            arr[i] = arr[mix];
            arr[mix] = temp;

        }
        System.out.println(Arrays.toString(arr));

 

3.插入排序

      int arr[] = {6,4,3,5,1,2};

        for (int i = 1 ; i < arr.length  ; i++){
            for (int j = i; j >0 ; j--){
                if(arr[j] < arr[j-1]){
                    int temp = arr[j];
                    arr[j] = arr[j-1];
                    arr[j-1] = temp;
                }else{
                    break;
                }
            }
        }
        System.out.println(Arrays.toString(arr));

  

高级排序

posted @ 2022-09-21 22:55  FinnYY  阅读(12)  评论(0编辑  收藏  举报