[Leedcode] [JAVA] [912 questions] [sort algorithm]

【Problem Description】

给你一个整数数组 nums,将该数组升序排列。
示例 1:
输入:nums = [5,2,3,1]
输出:[1,2,3,5]

[Thinking] answer

1. insertion sort (familiar)

Each time a digital insert an ordered array, become a longer length of an ordered array, after limited operations, ordered arrays as a whole.

  • Optimization: "a digital insert an ordered array" This step may not be used to gradually exchange, assigned to the first use of "temporary variables" and then after "appropriate elements" shift, vacated a position, and finally the "temporary variable strategy "assigned to the vacancy (that is, the above picture is meant). Coding time if not careful, will probably modify the value of the array, the proposed multi-commissioning

Time complexity: O (N ^ 2) space complexity: O (1)

public class Solution {

    // 插入排序:稳定排序,在接近有序的情况下,表现优异

    public int[] sortArray(int[] nums) {
        int len = nums.length;
        // 循环不变量:将 nums[i] 插入到区间 [0, i) 使之成为有序数组
        for (int i = 1; i < len; i++) {
            // 先暂存这个元素,然后之前元素逐个后移,留出空位
            int temp = nums[i];
            int j = i;
            // 注意边界 j > 0
            while (j > 0 && nums[j - 1] > temp) {
                nums[j] = nums[j - 1];
                j--;
            }
            nums[j] = temp;
        }
        return nums;
    }
}

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/sort-an-array/solution/fu-xi-ji-chu-pai-xu-suan-fa-java-by-liweiwei1419/
2. merge sort (focus)

With the extra space, merging two ordered arrays get longer and orderly array.
Time complexity: O (NlogN) space complexity: O (N)

  • Optimization 1: turn in "inter-cell" in use "insertion sort", Java source code which has a similar such operations, "inter-cell" is a super-length parameters, need to test decision, I refer here to the JDK source code;
  • Optimization 2: In the "two arrays' itself is ordered under the circumstances, consolidation is not needed;
  • Optimization 3: Use the full array of operating an interim "merge two ordered arrays", to avoid creating a temporary array of destruction and consumption, to avoid the calculation of index offset.
  • Note: When merge sort of realization, pay special attention not to implement this algorithm to a non-stable sort, the difference in <= and <, are specified in the code.
public class Solution {
    // 归并排序

    /**
     * 列表大小等于或小于该大小,将优先于 mergeSort 使用插入排序
     */
    private static final int INSERTION_SORT_THRESHOLD = 7;

    public int[] sortArray(int[] nums) {
        int len = nums.length;
        int[] temp = new int[len];
        mergeSort(nums, 0, len - 1, temp);
        return nums;
    }

    /**
     * 对数组 nums 的子区间 [left, right] 进行归并排序
     *
     * @param nums
     * @param left
     * @param right
     * @param temp  用于合并两个有序数组的辅助数组,全局使用一份,避免多次创建和销毁
     */
    private void mergeSort(int[] nums, int left, int right, int[] temp) {
        // 小区间使用插入排序
        if (right - left <= INSERTION_SORT_THRESHOLD) {
            insertionSort(nums, left, right);
            return;
        }

        int mid = left + (right - left) / 2;
        // Java 里有更优的写法,在 left 和 right 都是大整数时,即使溢出,结论依然正确
        // int mid = (left + right) >>> 1;

        mergeSort(nums, left, mid, temp);
        mergeSort(nums, mid + 1, right, temp);
        // 如果数组的这个子区间本身有序,无需合并
        if (nums[mid] <= nums[mid + 1]) {
            return;
        }
        mergeOfTwoSortedArray(nums, left, mid, right, temp);
    }

    /**
     * 对数组 arr 的子区间 [left, right] 使用插入排序
     *
     * @param arr   给定数组
     * @param left  左边界,能取到
     * @param right 右边界,能取到
     */
    private void insertionSort(int[] arr, int left, int right) {
        for (int i = left + 1; i <= right; i++) {
            int temp = arr[i];
            int j = i;
            while (j > left && arr[j - 1] > temp) {
                arr[j] = arr[j - 1];
                j--;
            }
            arr[j] = temp;
        }
    }

    /**
     * 合并两个有序数组:先把值复制到临时数组,再合并回去
     *
     * @param nums
     * @param left
     * @param mid   [left, mid] 有序,[mid + 1, right] 有序
     * @param right
     * @param temp  全局使用的临时数组
     */
    private void mergeOfTwoSortedArray(int[] nums, int left, int mid, int right, int[] temp) {
       //void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
        System.arraycopy(nums, left, temp, left, right + 1 - left);

        int i = left;
        int j = mid + 1;
//两条有序序列合并
        for (int k = left; k <= right; k++) {
//left     mid +1
//[1,1,2,3]  [5,6,7,8]  
 //边界 左边遍历完 右边还没开始 右边持续插入
            if (i == mid + 1) {
                nums[k] = temp[j];
//没能改变值 
                j++;
// [5,6,7,8]   [1,1,2,3]
//边界  右边遍历完 左边还没开始 左边持续插入
            } else if (j == right + 1) {
                nums[k] = temp[i];
                i++;
            } else if (temp[i] <= temp[j]) {
                // 注意写成 < 就丢失了稳定性(相同元素原来靠前的排序以后依然靠前)
                nums[k] = temp[i];
                i++;
            } else {
                // temp[i] > temp[j]
                nums[k] = temp[j];
                j++;
            }
        }
    }
}

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/sort-an-array/solution/fu-xi-ji-chu-pai-xu-suan-fa-java-by-liweiwei1419/

3. Quick Sort (focus)

Quicksort every time a scheduled element (this element should stay in its final position stay), then recursively go row portion of its left and right, in order to proceed, until an orderly array;
[pictures of foreign chains dump fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-bH18YcEd-1585662450983) ( https://upload-images.jianshu.io/upload_images/17025746-9d7d9ff3a2826052.png?imageMogr2/auto -orient / strip% 7CimageView2 / 2 / w / 1240)]

import java.util.Random;

public class Solution {

    // 快速排序 1:基本快速排序

    /**
     * 列表大小等于或小于该大小,将优先于 quickSort 使用插入排序
     */
    private static final int INSERTION_SORT_THRESHOLD = 7;

    private static final Random RANDOM = new Random();


    public int[] sortArray(int[] nums) {
        int len = nums.length;
        quickSort(nums, 0, len - 1);
        return nums;
    }

    private void quickSort(int[] nums, int left, int right) {
        // 小区间使用插入排序
        if (right - left <= INSERTION_SORT_THRESHOLD) {
            insertionSort(nums, left, right);
            return;
        }

        int pIndex = partition(nums, left, right);
        quickSort(nums, left, pIndex - 1);
        quickSort(nums, pIndex + 1, right);
    }

    /**
     * 对数组 nums 的子区间 [left, right] 使用插入排序
     *
     * @param nums  给定数组
     * @param left  左边界,能取到
     * @param right 右边界,能取到
     */
    private void insertionSort(int[] nums, int left, int right) {
        for (int i = left + 1; i <= right; i++) {
            int temp = nums[i];
            int j = i;
            while (j > left && nums[j - 1] > temp) {
                nums[j] = nums[j - 1];
                j--;
            }
            nums[j] = temp;
        }
    }

//版本 1:基本快排:把等于切分元素的所有元素分到了数组的同一侧,可能会造成递归树倾斜;
    private int partition(int[] nums, int left, int right) {
//避免有序数组 效率低下
////随机生成一个整数,这个整数的范围就是[0,right - left + 1)
        int randomIndex = RANDOM.nextInt(right - left + 1) + left;
        swap(nums, left, randomIndex);

        // 基准值
        int pivot = nums[left];
        int lt = left;
        // 循环不变量:
        // all in [left + 1, lt] < pivot
        // all in [lt + 1, i) >= pivot
        for (int i = left + 1; i <= right; i++) {
            if (nums[i] < pivot) {
                lt++;
                swap(nums, i, lt);
            }
        }
        swap(nums, left, lt);
        return lt;
    }
//版本 2:双指针快排:把等于切分元素的所有元素等概率地分到了数组的两侧,避免了递归树倾斜,递归树相对平衡;
 private int partition(int[] nums, int left, int right) {
        int randomIndex = left + RANDOM.nextInt(right - left + 1);
        swap(nums, randomIndex, left);

        int pivot = nums[left];
        int lt = left + 1;
        int gt = right;

        // 循环不变量:
        // all in [left + 1, lt) <= pivot
        // all in (gt, right] >= pivot
        while (true) {
            while (lt <= right && nums[lt] < pivot) {
                lt++;
            }

            while (gt > left && nums[gt] > pivot) {
                gt--;
            }

            if (lt > gt) {
                break;
            }

            // 细节:相等的元素通过交换,等概率分到数组的两边
            swap(nums, lt, gt);
            lt++;
            gt--;
        }
        swap(nums, left, gt);
        return gt;
    }


    private void swap(int[] nums, int index1, int index2) {
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }
}

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/sort-an-array/solution/fu-xi-ji-chu-pai-xu-suan-fa-java-by-liweiwei1419/

Version 3: three-hand quick drain: slicing element is equal to all elements of the array intermediate pushed in there are many sub-elements and cutting elements are equal in the case of recursive interval greatly reduced
-partition () merge into QUICKSORT ()

private void quickSort(int[] nums, int left, int right) {
      // 小区间使用插入排序
      if (right - left <= INSERTION_SORT_THRESHOLD) {
          insertionSort(nums, left, right);
          return;
      }

      int randomIndex = left + RANDOM.nextInt(right - left + 1);
      swap(nums, randomIndex, left);

      // 循环不变量:
      // all in [left + 1, lt] < pivot
      // all in [lt + 1, i) = pivot
      // all in [gt, right] > pivot
      int pivot = nums[left];
      int lt = left;
      int gt = right + 1;

      int i = left + 1;
      while (i < gt) {
          if (nums[i] < pivot) {
              lt++;
              swap(nums, i, lt);
              i++;
          } else if (nums[i] == pivot) {
              i++;
          } else {
              gt--;
              swap(nums, i, gt);
          }
      }
      swap(nums, left, lt);
      // 注意这里,大大减少了两侧分治的区间
      quickSort(nums, left, lt - 1);
      quickSort(nums, gt, right);
  }

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/sort-an-array/solution/fu-xi-ji-chu-pai-xu-suan-fa-java-by-liweiwei1419/

4. heap sort (heap is important to grasp heap sort based on individual circumstances)

Heap sort is selected to optimize sort, selection sort need to select the largest element (complexity of O (N) O (N)) by "Health Warning" approach is not scheduled sections, and "heap sort," put not scheduled to be part of building a "heap", so you can order O (logN) way O (\ log N) elect largest element;

  • Reference "Algorithm" heap section
public class Solution {

   public int[] sortArray(int[] nums) {
       int len = nums.length;
       // 将数组整理成堆
       heapify(nums);

       // 循环不变量:区间 [0, i] 堆有序
       for (int i = len - 1; i >= 1; ) {
           // 把堆顶元素(当前最大)交换到数组末尾
           swap(nums, 0, i);
           // 逐步减少堆有序的部分
           i--;
           // 下标 0 位置下沉操作,使得区间 [0, i] 堆有序
           siftDown(nums, 0, i);
       }
       return nums;
   }

   /**
    * 将数组整理成堆(堆有序)
    *
    * @param nums
    */
   private void heapify(int[] nums) {
       int len = nums.length;
       // 只需要从 i = (len - 1) / 2 这个位置开始逐层下移
       for (int i = (len - 1) / 2; i >= 0; i--) {
           siftDown(nums, i, len - 1);
       }
   }

   /**
    * @param nums
    * @param k    当前下沉元素的下标
    * @param end  [0, end] 是 nums 的有效部分
    */
   private void siftDown(int[] nums, int k, int end) {
       while (2 * k + 1 <= end) {
           int j = 2 * k + 1;
           if (j + 1 <= end && nums[j + 1] > nums[j]) {
               j++;
           }
           if (nums[j] > nums[k]) {
               swap(nums, j, k);
           } else {
               break;
           }
           k = j;
       }
   }

   private void swap(int[] nums, int index1, int index2) {
       int temp = nums[index1];
       nums[index1] = nums[index2];
       nums[index2] = temp;
   }
}

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/sort-an-array/solution/fu-xi-ji-chu-pai-xu-suan-fa-java-by-liweiwei1419/

5. Selection Sort

Selecting a minimum portion of each unscheduled exchange section to the beginning of the unscheduled most part, over several steps, the entire array can be scheduled. Namely: first select the smallest, and then select the second smallest, and so on.
Time complexity: O (N) space complexity: O (1)

  // 选择排序:每一轮选择最小元素交换到未排定部分的开头
import java.util.Arrays;

public class Solution {

    // 选择排序:每一轮选择最小元素交换到未排定部分的开头

    public int[] sortArray(int[] nums) {
        int len = nums.length;
        // 循环不变量:[0, i) 有序,且该区间里所有元素就是最终排定的样子
        for (int i = 0; i < len - 1; i++) {
            // 选择区间 [i, len - 1] 里最小的元素的索引,交换到下标 i
            int minIndex = i;
            for (int j = i + 1; j < len; j++) {
                if (nums[j] < nums[minIndex]) {
                    minIndex = j;
                }
            }
            swap(nums, i, minIndex);
        }
        return nums;
    }

    private void swap(int[] nums, int index1, int index2) {
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }

    public static void main(String[] args) {
        int[] nums = {5, 2, 3, 1};
        Solution solution = new Solution();
        int[] res = solution.sortArray(nums);
        System.out.println(Arrays.toString(res));
    }
}

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/sort-an-array/solution/fu-xi-ji-chu-pai-xu-suan-fa-java-by-liweiwei1419/
6. Hill sorting (not recommended to spend more time understanding)

Insertion sort optimization. In the insertion sort, the number after if on a smaller, it would have come in front of the exchange several times. "Hill sorting" to improve this approach. With intervals using insertion sort, until the last "interval" is 1 when the standard is the "insertion sort", this time in the array element is already "almost orderly"
time complexity of Shell sort of still no clear conclusion only a range

public class Solution {

    // 希尔排序

    public int[] sortArray(int[] nums) {
        int len = nums.length;
        int h = 1;

        // 使用 Knuth 增量序列
        // 找增量的最大值
        while (3 * h + 1 < len) {
            h = 3 * h + 1;
        }

        while (h >= 1) {
            // insertion sort
            for (int i = h; i < len; i++) {
                insertionForDelta(nums, h, i);
            }
            h = h / 3;
        }
        return nums;
    }

    /**
     * 将 nums[i] 插入到对应分组的正确位置上,其实就是将原来 1 的部分改成 gap
     *
     * @param nums
     * @param gap
     * @param i
     */
    private void insertionForDelta(int[] nums, int gap, int i) {
        int temp = nums[i];
        int j = i;
        // 注意:这里 j >= deta 的原因
        while (j >= gap && nums[j - gap] > temp) {
            nums[j] = nums[j - gap];
            j -= gap;
        }
        nums[j] = temp;
    }
}

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/sort-an-array/solution/fu-xi-ji-chu-pai-xu-suan-fa-java-by-liweiwei1419/

7. bubble sort (understand)

Each time through the outer loop pairwise comparison, the largest at the end of each round are not part of the elements into an array of scheduled

public class Solution {

    // 冒泡排序:超时

    public int[] sortArray(int[] nums) {
        int len = nums.length;
        for (int i = len - 1; i >= 0; i--) {
            // 先默认数组是有序的,只要发生一次交换,就必须进行下一轮比较,
            // 如果在内层循环中,都没有执行一次交换操作,说明此时数组已经是升序数组
            boolean sorted = true;
            for (int j = 0; j < i; j++) {
                if (nums[j] > nums[j + 1]) {
                    swap(nums, j, j + 1);
                    sorted = false;
                }
            }
            if (sorted) {
                break;
            }
        }
        return nums;
    }

    private void swap(int[] nums, int index1, int index2) {
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }
}

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/sort-an-array/solution/fu-xi-ji-chu-pai-xu-suan-fa-java-by-liweiwei1419/
8. counting sequencing (Learn)

Each value appearing do a count, then small to large orderly array output according to the count.
- maintaining stability approach is: prefixed to the array and to do the counting, when the assignment back to step 2, in accordance with data of the original input array assignment from back to front, prefixes, and each element of the array holds the stored index information (here not say too thin, had it not important, not difficult to understand).

Author: liweiwei1419
link: https: //leetcode-cn.com/problems/sort-an-array/solution/fu-xi-ji-chu-pai-xu-suan-fa-java-by-liweiwei1419/

public class Solution {

    // 计数排序

    private static final int OFFSET = 50000;

    public int[] sortArray(int[] nums) {
        int len = nums.length;
        // 由于 -50000 <= A[i] <= 50000
        // 因此"桶" 的大小为 50000 - (-50000) = 10_0000
        // 并且设置偏移 OFFSET = 50000,目的是让每一个数都能够大于等于 0
        // 这样就可以作为 count 数组的下标,查询这个数的计数
        int size = 10_0000;

        // 计数数组
        int[] count = new int[size];
        // 计算计数数组
        for (int num : nums) {
            count[num + OFFSET]++;
        }

        // 把 count 数组变成前缀和数组
        for (int i = 1; i < size; i++) {
            count[i] += count[i - 1];
        }

        // 先把原始数组赋值到一个临时数组里,然后回写数据
        int[] temp = new int[len];
        System.arraycopy(nums, 0, temp, 0, len);

        // 为了保证稳定性,从后向前赋值
        for (int i = len - 1; i >= 0; i--) {
            int index = count[temp[i] + OFFSET] - 1;
            nums[index] = temp[i];
            count[temp[i] + OFFSET]--;
        }
        return nums;
    }
}

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/sort-an-array/solution/fu-xi-ji-chu-pai-xu-suan-fa-java-by-liweiwei1419/
9. Selection Sort (Learn)
  • Sorting based on keywords, for example, numeric sort, bits, ten, one hundred is the keyword. For data sorted by date: year, month, day, hour, minute, second is the keyword
  • "Radix sort," uses a "count Sort"
public class Solution {

    // 基数排序:低位优先

    private static final int OFFSET = 50000;

    public int[] sortArray(int[] nums) {
        int len = nums.length;

        // 预处理,让所有的数都大于等于 0,这样才可以使用基数排序
        for (int i = 0; i < len; i++) {
            nums[i] += OFFSET;
        }

        // 第 1 步:找出最大的数字
        int max = nums[0];
        for (int num : nums) {
            if (num > max) {
                max = num;
            }
        }

        // 第 2 步:计算出最大的数字有几位,这个数值决定了我们要将整个数组看几遍
        int maxLen = getMaxLen(max);

        // 计数排序需要使用的计数数组和临时数组
        int[] count = new int[10];
        int[] temp = new int[len];

        // 表征关键字的量:除数
        // 1 表示按照个位关键字排序
        // 10 表示按照十位关键字排序
        // 100 表示按照百位关键字排序
        // 1000 表示按照千位关键字排序
        int divisor = 1;
        // 有几位数,外层循环就得执行几次
        for (int i = 0; i < maxLen; i++) {

            // 每一步都使用计数排序,保证排序结果是稳定的
            // 这一步需要额外空间保存结果集,因此把结果保存在 temp 中
            countingSort(nums, temp, divisor, len, count);

            // 交换 nums 和 temp 的引用,下一轮还是按照 nums 做计数排序
            int[] t = nums;
            nums = temp;
            temp = t;

            // divisor 自增,表示采用低位优先的基数排序
            divisor *= 10;
        }

        int[] res = new int[len];
        for (int i = 0; i < len; i++) {
            res[i] = nums[i] - OFFSET;
        }
        return res;
    }

    private void countingSort(int[] nums, int[] res, int divisor, int len, int[] count) {
        // 1、计算计数数组
        for (int i = 0; i < len; i++) {
            // 计算数位上的数是几,先取个位,再十位、百位
            int remainder = (nums[i] / divisor) % 10;
            count[remainder]++;
        }

        // 2、变成前缀和数组
        for (int i = 1; i < 10; i++) {
            count[i] += count[i - 1];
        }

        // 3、从后向前赋值
        for (int i = len - 1; i >= 0; i--) {
            int remainder = (nums[i] / divisor) % 10;
            int index = count[remainder] - 1;
            res[index] = nums[i];
            count[remainder]--;
        }

        // 4、count 数组需要设置为 0 ,以免干扰下一次排序使用
        for (int i = 0; i < 10; i++) {
            count[i] = 0;
        }
    }

    /**
     * 获取一个整数的最大位数
     *
     * @param num
     * @return
     */
    private int getMaxLen(int num) {
        int maxLen = 0;
        while (num > 0) {
            num /= 10;
            maxLen++;
        }
        return maxLen;
    }
}

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/sort-an-array/solution/fu-xi-ji-chu-pai-xu-suan-fa-java-by-liweiwei1419/

10. Selection Sort (Learn)
ublic class Solution {

    // 桶排序
    // 1 <= A.length <= 10000
    // -50000 <= A[i] <= 50000

    // 10_0000

    private static final int OFFSET = 50000;

    public int[] sortArray(int[] nums) {
        int len = nums.length;
        // 第 1 步:将数据转换为 [0, 10_0000] 区间里的数
        for (int i = 0; i < len; i++) {
            nums[i] += OFFSET;
        }

        // 第 2 步:观察数据,设置桶的个数
        // 步长:步长如果设置成 10 会超出内存限制
        int step = 1000;
        // 桶的个数
        int bucketLen = 10_0000 / step;

        int[][] temp = new int[bucketLen + 1][len];
        int[] next = new int[bucketLen + 1];

        // 第 3 步:分桶
        for (int num : nums) {
            int bucketIndex = num / step;
            temp[bucketIndex][next[bucketIndex]] = num;
            next[bucketIndex]++;
        }

        // 第 4 步:对于每个桶执行插入排序
        for (int i = 0; i < bucketLen + 1; i++) {
            insertionSort(temp[i], next[i] - 1);
        }

        // 第 5 步:从桶里依次取出来
        int[] res = new int[len];
        int index = 0;
        for (int i = 0; i < bucketLen + 1; i++) {
            int curLen = next[i];
            for (int j = 0; j < curLen; j++) {
                res[index] = temp[i][j] - OFFSET;
                index++;
            }
        }
        return res;
    }

    private void insertionSort(int[] arr, int endIndex) {
        for (int i = 1; i <= endIndex; i++) {
            int temp = arr[i];
            int j = i;
            while (j > 0 && arr[j - 1] > temp) {
                arr[j] = arr[j - 1];
                j--;
            }
            arr[j] = temp;
        }
    }
}

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/sort-an-array/solution/fu-xi-ji-chu-pai-xu-suan-fa-java-by-liweiwei1419/

【to sum up】

. ##### 1 ranking algorithm summary
[Picture dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-1VAMavOi-1585662450986) ( https: //upload-images.jianshu .io / upload_images / 17025746-64aa4a7d0e174744.png? imageMogr2 / auto-orient / strip% 7CimageView2 / 2 / w / 1240)]

1.1 Insertion Sort

  • Time complexity: O (N ^ 2) space complexity: O (1)
  • Pros: On the "almost orderly" array performed well, in particular, behave in a "short array" is also very good. Because the characteristics of "short array" is scheduled every element from its final position will not be too far away
  • Application: When performing the sort of tasks within the inter-cell can be turned using the "insertion sort"

1.2 merge sort

  • Time complexity: complexity O (NlogN) space: O (N)
    - algorithm idea: recursion, divide and conquer ideological problem solving in the field of algorithm is very common, by writing "merge sort" learning recursive thinking, understand recursion details familiar with the idea of partition, is a very good learning materials.
    - Benefits: "merge sort", "quick sort" than the good thing is, it means the extra space, you can achieve "stable sort", Java was sorting task for "array of objects", that is, using merge sort (an upgraded version of TimSort here do not introduced).

1.3 fast row

  • Time complexity: O (NlogN) space complexity: O (logN)
  • Algorithm idea: Divide and conquer (divide and conquer idea), and "merge sort" different, "quick sort" in "points" do not want to "merge sort" no brain to split in two on this matter, instead of using the partition method, Therefore, there is no process "together" in.
    [Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-BWOPzOP8-1585662450988) (https://upload-images.jianshu.io/upload_images/17025746-ad48df7591da38ac.png ? imageMogr2 / Auto-Orient / Strip% 7CimageView2 / 2 / w / 1240)]
    - Cons: Quick Sort lost stability, if you need a stable quick sort, you need to define the specific comparison function, a process called "stabilization" in here not carried out.
  • :( disadvantages for specific test cases: reverse order of the array or array) must randomization segmentation element (pivot), otherwise it is in the input array ordered array or array in reverse order when the quick sort will become very slow (equivalent to bubble sort or "selection sort");

1.4 heapsort

  • Time complexity: O (NlogN) space complexity: O (1)
  • Heap sort is the selection sort of optimization, select the sort required in unscheduled elected in part the largest element (complexity of O (N)) by "Health Warning" approach, and "heap sort," took part unscheduled build into a "heap", so you can order O (logN) is elected by the largest element;
  • Heap is a very interesting data structure, which in many languages ​​is also named as "priority queue." It is based on an array of "tree" structure, similar data structures as well as "disjoint-set", "tree line" and so on. "Priority queue" is a special queue, in order of priority from the team, from that point on that the "ordinary queue" no difference. "Priority queue" Arrays can be used to achieve, it can also be achieved with an ordered array, but as long as a linear structure, complexity will be high, therefore, "tree" structure have advantages, to achieve the best "priority queue" is "heap . "

1.5 Selection Sort

  • Time complexity: O (N ^ 2) space complexity: O (1)
  • Advantages: Minimum number of exchanges.
  • 1 algorithm idea: greedy algorithm: every decision just look at the current, the current optimal, the global optimum. Note: this idea is not applicable at all times.
  • ALGORITHM 2: Less Political Ideology: the outer loop every time a scheduled element, the scale of the problem is gradually reduced until fully resolved, that is, "of large and small, of the small." The use of "Political Ideology minus" typical algorithm is the famous "binary search."

1.6 Shell sort

  • Time complexity: not clear

1.7 bubble sort (understand)

  • Time complexity: O (N ^ 2) space complexity: O (1)
  • Pros: "bubble sort" has one characteristic: During traversal, Early detection arrays are ordered, ending sort, rather than the "selection sort" that, even if the input data is in order, "select sort "still need to" go through all the processes silly "places.

Selection Sort Sort Count 1.8 1.9 1.10 Selection Sort

  • Time complexity: O (N) optimization
  • Features: a place where the number is determined by the size of this number decision itself, it does not require comparison. It can also be considered a hash of thought: the value mapped address.
  • Features: certain additional space is needed to complete the task of sorting
  • Cons: Applicable scene much, mainly because of the use of these three sorting must ensure that each element of the input array are within a reasonable range
  • Advantages: stable sort may be implemented as, without stabilization
2. Code Specification

2.1 loop invariant (fast discharge)
- keep the "loop invariant" variable that is defined before the start of the cycle, cycle, after the end of the cycle, remain the same nature, the nature of the problem is defined in terms of man-made features.
"Basis to prove the effectiveness of the algorithm is to write the code to ensure compliance loop invariant, is not equal to the write number, the first exchange or the first ++ loop invariant, it would be particularly clear, never wrong, We will comply with the "loop invariant" written as a comment in the code.
2.2 "algorithm 4" code style is not recommended

  • The code is written posters, and should try to avoid the code of personal style, using standardized wording to ensure readability, scalability.
    [Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-ntkuZXCs-1585662450990) ( https://upload-images.jianshu.io/upload_images/17025746-5aba0141df398096.png ? imageMogr2 / Auto-Orient / Strip 7CimageView2% / 2 / W / 1240 is)]
    2.3 optimization variable name
  • lt is less than the abbreviation represents a (strictly) less than;
  • It is greater than gt abbreviation represents (strictly) greater than one;
  • le is less than or equal abbreviations, showing less (this code is not used);
  • is an abbreviation ge greater than or equal to, greater than or equal expressed (this code is not used).
3. Sort successful entry written interview do not panic
  public int[] sortArray(int[] nums) {
        Arrays.sort(nums);
        return nums;
    }
Amway website:

Algorithm for dynamic presentation

Reference link: https: //leetcode-cn.com/problems/sort-an-array/solution/fu-xi-ji-chu-pai-xu-suan-fa-java-by-liweiwei1419/

Published 22 original articles · won praise 0 · Views 412

Guess you like

Origin blog.csdn.net/dadongwudi/article/details/105233093
912