quick sort

 1 C++
 2 void quickSort(int arr[], int left, int right) {
 3       int i = left, j = right;
 4       int tmp;
 5       int pivot = arr[(left + right) / 2];
 6  
 7       /* partition */
 8       while (i <= j) {
 9             while (arr[i] < pivot)
10                   i++;
11             while (arr[j] > pivot)
12                   j­­;
13             if (i <= j) {
14                   tmp = arr[i];
15                   arr[i] = arr[j];
16                   arr[j] = tmp;
17                   i++;
18                   j­­;
19             }
20       };
21  
22       /* recursion */
23       if (left < j)
24             quickSort(arr, left, j);
25       if (i < right)
26             quickSort(arr, i, right);
27 }
View Code

 

Quicksort is a fast sorting algorithm, which is used not only for educational purposes,but widely applied in practice. On the average, it has O(n log n) complexity, makingquicksort suitable for sorting big data volumes. The idea of the algorithm is quite simple and once you realize it, you can write quicksort as fast as bubble sort.Forum Feedback C++ code snippets Economics Textbook Support us to write more tutorials AlgorithmThe divide-and-conquer strategy is used in quicksort. Below the recursion step is described:1. Choose a pivot value. We take the value of the middle element as pivot value, but it can be any value, which is in range of sorted values, even if it doesn't present in the array.2. Partition. Rearrange elements in such a way, that all elements which are lesser than the pivot go to the left part of the array and all elements greater than the pivot, goto the right part of the array. Values equal to the pivot can stay in any part of the array. Notice, that array may be divided in non-equal parts.3. Sort both parts. Apply quicksort algorithm recursively to the left and the right parts.Partition algorithm in detail to create new visualizers to keep sharing free knowledge for youThere are two indices i and j and at the very beginning of the partition algorithm i pointsto the first element in the array and j points to the last one. Then algorithm moves i forward, until an element with value greater or equal to the pivot is found. Index j is moved backward, until an element with value lesser or equal to the pivot is found. If i ≤j then they are swapped and i steps to the next position (i + 1), j steps to the previousone (j - 1). Algorithm stops, when i becomes greater than j.After partition, all values before i-th element are less or equal than the pivot and allvalues after j-th element are greater or equal to the pivot.Example. Sort {1, 12, 5, 26, 7, 14, 3, 7, 2} using quicksort.

posted @ 2016-08-18 07:01  PKICA  阅读(153)  评论(0编辑  收藏  举报