Quick Sort and Merge Sort

Quick sort and merge sort are things that are often asked during interviews. For any of these knowledge points, you must answer them like a flow, such as hand push, time complexity, principle, etc. Below I will summarize the knowledge points frequently asked in these two sorting.

quicksort

The quick sort code is as follows (to be memorized and understood):

private static int Partition(int[] arr, int left, int right) {
        //arr[left]为挖的第一个坑
        int key = arr[left];
        while (left< right) {
            while (arr[right] >= key && right> left)
                end--;
            arr[left] = arr[right];
            while (arr[left] <= key && right> start)
                left++;
            arr[right] = arr[left];
        }
        arr[left] = key;
        return left;
} 

public static void quickSort(int[] arr, int left, int right) {
        if (left < right){
            int index = Partition(arr, left, right);
            quickSort(arr, left, index - 1);
            quickSort(arr, index + 1, right);
        }
 }

Algorithm principle reference: https://blog.csdn.net/kwang0131/article/details/51085734

Average O(nlog2n)
Worst O(n2)
Best O(nlog2n)
Space Complexity O(nlog2n)
Unstable
More complicated

merge sort

The merge sort code is as follows (to memorize and understand):

public static void merge(int[] a, int left, int mid, int right) {
        int[] temp = new int[right- left + 1];
        int i = left;// 左指针
        int j = mid + 1;// 右指针
        int k = 0;
        // 把较小的数先移到新数组中
        while (i <= mid && j <= right) {
            if (a[i] < a[j]) {
                temp[k++] = a[i++];
            } else {
                temp[k++] = a[j++];
            }
        }
        // 把左边剩余的数移入数组
        while (i <= mid) 
            temp[k++] = a[i++];
        }
        // 把右边边剩余的数移入数组
        while (j <= right) {
            temp[k++] = a[j++];
        }
        // 把新数组中的数覆盖nums数组
        for (int k2 = 0; k2 < temp.length; k2++) {
            a[k2 + left] = temp[k2];
        }
    }

    public static void mergeSort(int[] a, int left, int right) {
        int mid = (left + right) / 2;
        if (left < right) {
            // 左边
            mergeSort(a, left, mid);
            // 右边
            mergeSort(a, mid + 1, right);
            // 左右归并
            merge(a, left, mid, right);
            System.out.println(Arrays.toString(a));
        }
    }

    public static void main(String[] args) {
        int a[] = {51, 46, 20, 18, 65, 97, 82, 30, 77, 50};
        mergeSort(a, 0, a.length - 1);
        System.out.println("排序结果:" + Arrays.toString(a));
    }
}

Algorithm principle reference: https://blog.csdn.net/lemon_tree12138/article/details/51517753

Average O(nlog2n)
Worst O(nlog2n)
Best O(nlog2n)
Space Complexity O(n)
Stable
More complicated

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325345117&siteId=291194637