Write quick sorting by yourself

Source: Internet
Author: User
Writing a quick sorting algorithm by yourself is not complex, but it is the most error-prone code when writing code. If you do not write it, it is easy to generate loops or divide errors. Therefore, I am very impressed when I write more by myself. I. Preliminary Research-simple fast Sorting Algorithm

void quick_sort(int a[], int l, int u){    if (l >= u) return;    int m = l;    for (int i=l+1; i<=u; i++) {        if (a[i] < a[l])            swap(a, i, ++m);    }    swap(a, l, m);    quick_sort(a, l, m-1);    quick_sort(a, m+1, u);}

ThisSimple quick sortingThere is a defect that in some extreme cases, such as when all elements are equal (or the elements themselves are ordered, such as 1, 2, 4, 5, etc ), the time complexity of the simple algorithm is O (n ^ 2 ).

Ii. Improvement-quick Sorting Algorithm Based on bidirectional Division

One improvement method is to useBidirectional DivisionUse two variables, I and J, I, to scan from left to right and move an excessively small element. When a large element is found to stop, J scans from right to left and moves an excessively large element to stop a small element. Then, test whether I and j are crossed. If yes, stop. Otherwise, the element values corresponding to I and j are exchanged. Note: If the array contains the same element, when the same element is encountered, we stop scanning and exchange the element values of I and J. HoweverIncrease in the number of exchangesBut the worst case of all elements being the same is changed from O (N ^ 2) to almost O (nlgn. For example, if array A = {, 2}, the simple and fast sorting method is used, each time n elements are divided into one group, one group, and one group, n-1, the time complexity is O (n ^ 2). After two-way division, the first division is 2, which can basically be balanced. The Code is as follows:

Void quick_sort_2 (int A [], int L, int U) {If (L> = u) return; int I = L; Int J = u + 1; int T = A [l]; // select the leftmost element as the pivot element while (1) {do {I ++ ;} while (A [I] <t & I <= U); // note that the condition I <= u cannot cross the border. Do {J --;} while (A [J]> T); if (I> J) break; swap (A, I, j);} swap (A, l, j); // note that l and J are exchanged here, instead of L and I, because after I crosses J, a [I... u] is greater than or equal to the Hub yuan t, and the hub yuan is on the far left, so it cannot be exchanged with I. It can only be exchanged with J. Quick_sort_2 (A, L, J-1); quick_sort_2 (A, J + 1, U );}

Although bidirectional division solves the problem that all elements are the same, for an array with sorted orders, such as 1, 2, 3, 4, and 5, this method still achieves O (N ^ 2) complexity.In addition, the two-way division should pay attention to the circular writing in the Code. If it is written in the while (A [I] <t) {I ++;} and other forms, because when both left and right values are equal to the Hub element, an endless loop occurs.

Iii. Continuous Improvement-Randomization Pivot Element

To solve the above problems, we can further improveRandomly select hub ElementTo improve the performance. Of course, there are also common methodsGetting three numbers. In addition, when data is basically sorted, insertion sorting can achieve good performance, and insertion sorting is faster than fast sorting when sorting small subarrays. You can use the Randomization pivot element and insertion sorting to comprehensively improve the quick sorting. The Code is as follows:

/* Modified quick sorting */void quick_sort_3 (int A [], int L, int U) {If (u-l <7) return insert_sort (A, L, U ); // if the number of elements is less than 7, call the insert sort swap (A, L, randint (L, u); // select the hub element int I = L at random; int J = u + 1; int T = A [l]; while (1) {do {I ++ ;} while (A [I] <t & I <= U); do {J --;} while (A [J]> T); if (I> J) break; swap (A, I, j);} swap (A, L, J); quick_sort_3 (A, L, J-1); quick_sort_3 (A, J + 1, U );} /* returns a random number in the range of [L, u */INT randint (int l, int U) {srand (Time (null); Return rand () % (u-L + 1) + L;}/* Insert sorting implementation */void insert_sort (int A [], int L, int U) {cout <"insert_sort" <Endl; For (INT I = L; I <u; I ++) {for (Int J = I + 1; j> L & A [J-1]> A [J]; j --) Swap (A, J, J-1 );}}

4. Explore again-use the three-digit Sampling Method

In addition to the Randomization pivot element, you can also use the three-digit method. The three-digit method refers to the array a [left... right], select the left, middle, and right values for sorting, and use the value as the pivot element. For example, if array A = {1, 3, 5, 2, 4}, we sort a [0], a [2], and a [4, select the value a [4] as the pivot element, and sort the array in the three-digit fetch to a = {1, 3, 4, 2, 5 }. We select the sorted a [2] = 4 as the pivot element, and switch it to the right-1 position, that is, location 3, so that the final array becomes a = {1, 3, 2, 4, 5}, and then you can start from I = 1 and J = 2 for quick sorting.

/* Algorithm for getting three numbers */INT median3 (int A [], int left, int right) {int center = (left + right)/2; /* triplicate sorting */if (a [left]> A [center]) Swap (A, left, center); if (a [left]> A [right]) swap (A, left, right); if (a [center]> A [right]) Swap (A, center, right);/* assert: A [left] <= A [center] <= A [right] */swap (A, center, right-1 ); // switch hub element to location right-1 return a [Right-1]; // return hub element}

Use the quick sorting of the three numbers as follows:

Void quick_sort_4 (int A [], int L, int U) {If (u-l <7) return insert_sort (A, L, U); int substring = median3 (, l, U); // obtain the pivot element int I = L, j = u-1; while (1) {While (A [++ I] <distinct ); while (A [-- J]> values); if (I> J) break; swap (A, I, j);} swap (A, I, U-1 ); // note that here is I with the hub element position U-1 exchange, because here is the choice of U-1 as the hub element, with the front select L as the hub element different quick_sort_4 (A, L, I-1 ); quick_sort_4 (A, I + 1, U );}

V. Non-recursive write quick sorting

Quick sorting by non-recursive writing is rare, but it is always good. Stack needs to be used. Pay attention to the order of stack pressure. The Division function is extracted to facilitate multiple calls. The Code is as follows:

Void quick_sort_5 (int A [], int L, int U) {If (L> = u) return; stack <int> S; // stack storage partition location int left = L, Right = u; int P = partition (A, left, right); If (p-1> left) {// two boundary values of the left half are added to stack S. push (p-1); S. push (left);} If (p + 1 <right) {// two boundary values in the right half of the stack are imported into Stack S. push (right); S. push (p + 1);} while (! S. empty () {// If the stack is not empty, Left = S. top (); S. pop (); Right = S. top (); S. pop (); P = partition (A, left, right); If (p-1> left) {S. push (p-1); S. push (left);} If (p + 1 <right) {S. push (right); S. push (p + 1) ;}}/ * Division function, return the pivot element position */INT partition (int A [], int L, int U) {int M = L; For (INT I = L + 1; I <= u; I ++) {if (a [I] <A [l]) swap (A, I, ++ m);} swap (A, l, m); Return m ;}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.