Sort (2) Quick Sort

1. Thought

step1. Pick out an element from the sequence, called a "pivot".

Step2. Partition: Reorder the sequence, all elements smaller than the reference value are placed in front of the reference, and all elements larger than the reference value are placed at the back of the reference (the same number can go to either side).

step3. Recursively sort the subsequence to the left of the reference value and the subsequence to the right.

insert image description here

1.1 Specific implementation

step1. Take the leftmost as the reference value, and use a[low] as the pivot
step2. The value of j starts with low+1, and i starts to loop from j, and points j to the first value larger than the pivot. If one is smaller than pivot, replace step3 with a[i] and a[j]
. At the end of the cycle, a[low] is pivot, and the values ​​from a[low+1] to a[j-1] are all less than pivot, The values ​​to the right of j are all greater than pivot. swap a[low] with a[j-1]
insert image description here

        void swap(int& a, int& b)
        {
    
    
            int t = a;
            a = b;
            b = t;
        }

        int partition(int arr[], int low, int high)
        {
    
    
            int pivot = arr[low]; // pivot
            int j = low+1; // Index of smaller element and indicates the right position of pivot found so far

            for (int i = j; i <= high; i++)
            {
    
    
                // If current element is smaller than the pivot
                if (arr[i] < pivot)
                {
    
    
                    swap(arr[j], arr[i]);
                    j++; // increment index of smaller element
                }
            }
            swap(arr[j-1], arr[low]);
            return (j-1);
        }
       
        void quickSort(int A[], int low, int high) //快排母函数
        {
    
    
            if (low < high) {
    
    
                int pivot = partition(A, low, high);
                quickSort(A, low, pivot - 1);
                quickSort(A, pivot + 1, high);
            }
        }
        
        void test() {
    
     
	        int a[] = {
    
     1, 4, 5, 2, 10, 8 };
	        int nSize = sizeof(a) / sizeof(int);
	        quickSort(a, 0, nSize-1);
        }

eg.

数组: 4 2 5 3 10 
pivot: 4


开始:
4 2 5 3 10
  j
   
->
4 2 5 3 10
    j      
->
4 2 3 5 10
      j
         
循环结束:再将a[low] 与a[j-1]互换->
3 2 4 5 10

[quote]

[1] Code quickSort.h

Guess you like

Origin blog.csdn.net/thefist11cc/article/details/123587167