Common sorting algorithm-quick sort

Introduction

  Quick sort is actually an improvement to bubble sorting. The array to be sorted is divided into two parts by one sort, and all the data in one part is smaller than all the data in the other part, and then the two parts of data are separated. For quick sorting, the entire sorting process is recursive, and eventually the entire array is ordered.

principle

  The principle of the quick sort algorithm is to select an element as the reference value. Generally, the first element of the array is selected, and the element larger than the reference value is placed on the right side of the array, and the element smaller than the reference value is placed on the left side of the array. The specific process is as follows:

  Compare from back to front, find elements smaller than the reference value, and exchange the reference value with the current element.

  Compare from front to back, find the element larger than the reference value, and exchange the reference value with the current element.

  Repeat the above process until the index compared from front to back and the index value compared from back to front are equal. For the reference value, the data on the left are less than or equal to the reference value, and the data on the right are greater than or equal to the reference value.

  Quickly sort the arrays on the left and right sides of the reference value until the entire array is ordered.

program

public class QuickSort {
    public static void sort(int[] arr){
        if(arr == null || arr.length == 0)
            throw new IllegalArgumentException("error");
        quickSort(arr, 0, arr.length-1);
    }
    public static void quickSort(int[] arr, int start, int end){
        int l = start;
        int r = end;
        int key = arr[start];
        while(l < r){
            while(l < r && arr[r] >= key)
                r--;
            if(arr[r] <= key){
                swap(arr, l, r);
            }
            while(l < r && arr[l] <= key)
                l++;
            if(arr[l] >= key){
                swap(arr, l, r);
            }
        }
        if(start < l)
            quickSort(arr, start, l-1);
        if(r < end)
            quickSort(arr, r+1, end);
    }
    private static void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

to sum up 

  The worst-case time complexity of quick sort is O (n ^ 2), the best case is O (nlogn), and the average time complexity is O (nlogn).

  Due to recursive calls, O (logn) is the best case for quick sort space complexity and O (n) is the worst case. Some people say that the space complexity of quick sort is O (nlogn), perhaps because of the recursive call O (logn) * array size O (n) ?.

  Since quick sorting will swap two non-adjacent elements, quick sorting is unstable.

Guess you like

Origin www.cnblogs.com/silentteller/p/12758059.html