How to write a better quick sorting program and a better sorting program

Source: Internet
Author: User

How to write a better quick sorting program and a better sorting program
Write a better quick sorting program

  • Quick sorting is one of the common sorting algorithms, but it is not that easy to write a fast and accurate application.
Precautions
  • First, you must write it correctly. Recursive Implementation is usually used. Recursion is equivalent to binary tree expansion. Therefore, if iteration is required, a queue is used to store subsequent traversal information.
  • A sequence value is needed for quick sorting. If sequence is selected, the complexity of N ^ 2 is easy. If a random number is used, the effect is best, but the overhead is too large, it is more appropriate to adopt the three-digit mean value method. The three-digit mean value method selects the first value, the last value, and the value in the middle of the array. Some documents show that the running time can be increased by 5%.
  • When the length of the array is small, such as less than 10 elements, it is best to use insert sorting or select sorting to prevent overhead caused by multiple function calls. The number of layers in recursion always decreases, so it is necessary to do so.
  • When merging the two parts of the array, use the two-side folder method to find a value greater than or less than the two parts and then exchange. Compared with normal conditions, if a value smaller than the limit value is found, the exchange can improve the running efficiency.
Implementation Code
  • The Code is as follows. It includes three auxiliary functions: insert sorting insert_sort, recursive function, and three-point value function.
  • In fact, the triplicate function uses insert sorting. Determine the value through three comparisons.
  • The interpolation algorithm uses the Temporary Variable tmp to avoid a large number of swap function calls.
#include<iostream>#include<iomanip>#include<vector>#include<cstdlib>#include<ctime>#include<algorithm>using namespace std;inline void swap(vector<int>& num, int p, int q){    int t = num[p];    num[p] = num[q];    num[q] = t;}void insert_sort(vector<int>& num){    int tmp, j;    for (int i = 1; i < num.size(); i++){        tmp = num[i];        for (j = i - 1; j >= 0 && num[j] > tmp; j--)            num[j + 1] = num[j];        num[j + 1] =tmp;    }}int quick_sort_sub(vector<int>& num, int p, int q){    if (p >= q)        return 0;    // if 4 elements or less, use insert sort    if (p + 10 > q){        vector<int> tnum(num.begin() + p, num.begin() + q + 1);        insert_sort(tnum);        for (int i = 0; i < tnum.size(); i++)            num[p + i] = tnum[i];    }    int idx = quick_three_partition(num, p, q);    swap(num, idx, q);    int pivot = num[q];    int left = p, right = q - 1;    while (1){        while (num[left] < pivot)            ++left;        while (num[right] >= pivot)            --right;        if (left < right)            swap(num, left, right);        else            break;    }    swap(num, left, q);    quick_sort_sub(num, p, left - 1);    quick_sort_sub(num, left + 1, q);    return left;}void quick_sort(vector<int>& num){    quick_sort_sub(num, 0, num.size() - 1);}int main(){    const int n = 10;    /*int num_array[n]= {2,1};    vector<int> num(num_array, num_array + n);*/    srand( time(NULL) );    vector<int> num(n);    for (auto& e : num)        e = rand() % n;    quick_sort(num);    for (auto& e : num)        cout << setw(4) << e << ' ';    cout << endl;    cout << "vector is sorted? : " << is_sorted(num.begin(), num.end()) << endl;    return 0;}

 
 

Reprinted by: Focustc. The blog address is http://blog.csdn.net/caozhk. The original link is opened by clicking
Write a sort program

3.5 fast sorting

Tony Hoare first proposed a fast Sorting Algorithm in 1962. The Research on the fast sorting method shows that the fast sorting algorithm is still the most practical one. Other sorting algorithms are better than quick sorting algorithms only when the input data items have more detailed information. The quick sorting algorithm is a typical example of the use of the divide and conquer technology. the random divide and conquer strategy is the basis for designing effective algorithms for a combination of optimization and calculation of geometric issues. Divide the rule into three steps:

(1) divide the problem into subproblems of equal size;

(2) independently solving these subproblems;

(3) Merge sub-problems into the solution of the original problem.

The basic idea of fast sorting is: first we select a median value middle (we can use the median value in the Program), and place the median value smaller than the median value on its left, and the median value greater than the median value on its right. Due to the complexity of this sorting algorithm, we first provide a program framework for sorting (available from various data structures ):
Void QuickSort (int * pData, int left, int right)
{
Int I, j;
Int middle, iTemp;
I = left;
J = right;

Middle = pData [(left + right)/2]; // calculates the median value.
Do
{
While (pData [I] <middle) & (I <right) // The number of scans from the left greater than the value
I ++;
While (pData [j]> middle) & (j> left) // Number of scans from the right that are less than the value
J --;
If (I <= j) // a pair of values is found.
{
// Exchange
ITemp = pData [I];
PData [I] = pData [j];
PData [j] = iTemp;
I ++;
J --;
}
} While (I <= j); // If the subscripts on both sides of the scan are staggered, stop (once completed)

// When the left part has a value (left <j), recursive left half edge

If (left <j)
QuickSort (pData, left, j );
// When the right part has a value (right> I), recursive right Half Edge
If (right> I)
QuickSort (pData, I, right );
}

It can be seen that the above sorting algorithm adopts a recursive strategy. Based on the above functions, we can re-write a function that matches our application framework and dynamically display the change process in the customer area of the dialog box:
Void QuickSort (int objectName [], CDC & dc, int left, int right)
{
Int I, j;
Int middle, iTemp;
I = left;
J = right;

Middle = sortObject [objectName [(left + right)/2]. iNumber; // calculates the median value
Do
{
While (sortObject [objectName [I]. iNumber <middle) & (I <right ))
// The number of scans from the left greater than the value
I ++;
While (sortObject [objectName [j]. iNumber> middle) & (j> left ))
... The remaining full text>
 
I want to write a program that uses C ++ to write fast sorting, from large to small, and I want to write it to me as soon as possible.

/*
Quick Sort. There are a bunch of online searches. Algorithms are just an idea or a method, not a C language. The same is true for other languages.
Fast sorting is also a bit like a two-way merge: Randomly retrieve a value q from an unordered sequence as the pivot point, then put the value greater than q on one side, and the value less than q on the other side of q, then, q is used as the demarcation point to determine the two sides of q.
Sort (during the fast sorting, re-set the pivot points on both sides of q, sort them, and then set the pivot points until the pivot points are sorted on both sides. That is, when there is only one number on both sides of the Fulcrum)
*/
# Include <stdio. h>
# Include <stdlib. h>
Int Qsort (int p [], int beg, int end)
{
If (beg + 1> = end) return 0; // exit Recursion
Int low, hight, q;
Low = beg;
Hight = end;
Q = p [low]; // q is the pivot. In fact, q can be a random number. But the following procedures will be changed.
While (1 ){
While (low If (low> = hight) break;
P [low ++] = p [hight];
While (low P [hight ++] = p [low];
}
P [low] = q;
Qsort (p, beg, low-1 );
Qsort (p, low + 1, end );
}
Int main ()
{
Int I, a [] = {54,654, 544,334 };
Qsort (a, 0, sizeof (a)/4-1 );
For (I = 0; I <sizeof (a)/4; I ++) printf ("% d", a [I]);
System ("pause ");
Return 0;
}
The advantage of quick sorting is related to the selection of pivot elements.
The selected pivot element is first or last after each recursion. This is the worst case.
We know the general sorting. (For example, bubble ..) Sort in an array p [m, n. Are to determine the maximum or minimum, and to determine the maximum (minimum) to be compared through the n-m-1.
And the whole process is almost (n-m-1 )! Time comparison.
In fast sorting: A comparison can determine the position of the pivot element. If p [m, q, n] (q is the pivot element ). Of course determine the first element is also to compare (n-m-1) times. But the second, the third (second layer) is the (q-m-1) and (n-q-1) times of comparison.
Obviously, if the q value is m or n, fast sorting has no advantage.

After reading the LS answer, I still have the highest level ...... Oh, thick, thick ...... Hope to adopt it! Bow ......

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.