Implementation and comparison of various types of sorting

Source: Internet
Author: User
Tags benchmark

Insert Sort Method:

Brief introduction: The insertion sort will divide the entire array into sorted and unordered parts during sorting. Take a number at the beginning of the never-sorted section and insert it into the sorted section.

Nature: is a stable sorting method. And the worst case altogether to move (1+2+...+n-1) = (n^2-n)/2 times, so basically is O (n^2) Complexity of the sorting method, of course, the order of input data can greatly affect the complexity of the sorting algorithm. For example, the data is in ascending order, all the data do not move, at this time only to judge N times to end the algorithm run.

Reference code:

void insert_sort (int *a,int  n) {    for (int1; i < n;i++) {        int v = a[i],j=i-1;          while (j>=0&&a[j]>v) {            1] = a[j];            J--;        }         1] = v;    }}
Bubble Sort Method:

Brief introduction: The sorting process also divides the array into sequential and unordered parts. Each time you start from the end of the array, compare the size of the adjacent two elements, and, in reverse order, exchange them.

Nature: Also a stable sort. In the worst case, it also needs to be done (n-1+n-2+...+1) = (n^2-n)/2 order, so it belongs to the O (n^2) complexity algorithm. In the bubble sort, each two number exchange order, will reduce an inverse pair, so the number of bubble method is the number of inverse pairs of the sequence. When the algorithm is implemented, a flag is added to determine if there is a reverse order in the last loop, and if not, the instructions are already queued. Without flag, no matter how the input data changes, the bubble sort requires (n^2-n)/2 order.

Reference code:

voidBubble_sort () {BOOLFlag =1;  for(inti =0; flag;i++) {flag=0;//used to determine whether there are reverse, there are exchange instructions and reverse order, if there is no reverse order, direct out of the loop         for(intj = N-1; J >= i +1; j--) {            if(a[j]<a[j-1]) swap (a[j], a[j-1]), flag =1; }    }}
Select the sorting method:

Brief introduction: The sorting process is divided into sorted and unsorted two parts. Each time you never send a good element, pick one of the smallest and the first in the not-so-good part of the data exchange.

Nature: An unstable sort, because the selection sort may exchange two positions that are not adjacent to the element. No matter how the input data changes, using the selection sort requires (n^2-n)/2 operations.

Reference code:

void Select_sort () {    for (int0; i < n; i++) {        int min_num = INF, K;          for (int j = i; J < N; j + +) {            if (Min_num > a[j]) min_num = A[j], k = j;
    
     }        swap (A[i], a[k]);}    }
    
Hill Sort Method:

Brief introduction: The Hill Sort method has fully exerted the character of the sequential data which can be processed quickly by inserting sort. Sets an interval array g={1,4,13,..., k},k<n, with each insertion sorted by interval.

Properties: The interval array is obtained well and the general complexity is maintained at O (n^1.25).

Reference code:

vector<int>G;voidInsert_sort (int*a,intNintg) {//where g represents the interval     for(inti = g; I < n;i++) {        intj = i-g,v=A[i];  while(j>=0&&a[j]>v) {a[j+ g] =A[j]; J-=G; } a[j+ g] =v; }}voidShell_sort () {intg =1;  while(g<N) {g.push_back (G); G=3* g +1; }     for(inti = g.size ()-1; I >=0; i--) {Insert_sort (A, n, G[i]); }}
Merge Sort method:

Simple introduction: Divide and conquer the idea, to deal with the length of the series of N, first divides the sequence of the right and left two parts, each part N/2 elements, each part is arranged sequentially, the linear time can complete the arrangement of n elements.

Nature: Merge sort is a stable sort. n data will be roughly divided into the log (n) layer, each layer execution time complexity is n, so the overall Nlog (n) complexity. The complexity recursion is the T (n) =2t (N/2) +n, and the computational complexity can also be used to make use of the main theorem. However, the merge sort requires extra space to use O (n).

Reference code:

voidMerge_sort (intLintR) {//[L,r]    if(R-l <=1)return; intMid = (L + r) >>1;    Merge_sort (L, mid);    Merge_sort (Mid, R); intp = L, q = mid,i=l;  while(p<mid| | q<r) {if(q>=r| | P&LT;MID&AMP;&AMP;A[P]&LT;A[Q]) t[i++] = a[p++]; Elset[i++] = a[q++]; }     for(inti = l; I < r;i++) {A[i]=T[i]; }}
Quick Sort Method:

Brief introduction: The idea of divided treatment. For n elements of the sequence, first found a benchmark E, the element larger than E is on the right, the element smaller than E is on the left of E, followed by e as the dividing point, recursive division [l,e], [E,r] part of the sequence.

Properties: Because the segmentation will exchange non-adjacent elements, so the fast row is an unstable sort. And does not require additional space, is a in-situ algorithm. The selection of the benchmark is the key to the speed of the algorithm, if the benchmark can be evenly divided two of molecular columns each time, the complexity of Nlog (n), if extreme conditions, there may still be O (n^2) complexity.

Reference code:

intPartitionintLintR) {//dividing the interval [l,r] with a datum    inti = L-1, e=A[r];  for(intj = L; J < r;j++) {        if(A[j] <e) {i++; swap (A[i], a[j]); }} swap (A[i+1], a[r]); returni +1;}voidQuick_sort (intLintR) {//[L,r]    if(L >= R)return; intE =partition (L, R); Quick_sort (l, E-1); Quick_sort (e+1, R);}
Counting sorting method:

Brief introduction: An array of C is created, and all occurrences of the element are recorded in C, such as an element x, c[x]++. After the sum of the elements in C, so that a certain c[k]=p, that is, the element is less than or equal to K and P, so that k is the small element of P, can directly know where it is.

Nature: a stable sort. The complexity is O (n+k), where k represents the largest element value in all elements.

Reference code:

int C[n_max], B[n_max]; void Count_sort () {    for (int0; i < n; i++) c[a[i]]++;       for (int11];      for (int0; i<n; i++) {        b[--c[a[i]] [= a[i];    }}

Heap Sorting Method:

First you need to introduce the heap:

The heap is the first complete binary tree, that is, the bottom layer of the node is all concentrated in the left several positions of the layer, the remaining layer of the number of nodes is full. Second, the nature of the maximum heap is that the key value of any node in the heap is less than the key value of its parent node, so the root node is the node with the largest key value in the maximum heap. Depending on the nature of the heap, you can store the heap with an array of subscripts starting at 1.

Next three blocks of content: heap construction, heap element insertions, and heap elements thrown.

1: Construction of the heap

For an array of n elements, how to adjust it to a heap: from the last node in the heap that has a son node (that is, a node numbered N/2), it adjusts to the root node, and each time a node is adjusted, a subtree with that node as its root is a heap. So it can be known that each time a node is adjusted, its left and right sons have satisfied the definition of the heap. Now to set the key value of the current node to the left and right son and its own key value in the maximum value, such as the original left son key value is the largest, the left son's key value and the current node's key value Exchange, and then recursively adjust the left son of the tree. If you resize an unordered array to a heap, you have to adjust the N/2 times to a total complex of O (n). Complexity Simple Description: If it is a perfect binary tree, a total of n nodes, then we first to the height of 1 n/2 sub-tree to adjust the operation, and then the height of 2 n/4 sub-tree to adjust. So the overall action to be performed is:N*σ1<=k<=logn (k/2^k) =o (n)

Reference code:

voidHeap_adjust (int*a,inti) {//to adjust the subtree of node I as the root node    intleft = (i <<1), right = (i <<1) +1, largest; if(Left<=n&&a[left]>a[i]) largest =Left ; Elselargest =i; if(Right<=n&&a[right]>a[largest]) largest =Right ; if(Largest! =i) {swap (a[largest], a[i]);    Heap_adjust (a,largest); }}intMain () {CIN>>N;  for(inti =1; I <= N; i++) Cin >>A[i];  for(inti = n/2; I >=1; i--) Heap_adjust (A, I);//start adjusting from the last node with a son node     for(inti =1; I <= N; i++) cout << A[i] <<" "; return 0;}

2: The elements of the heap are inserted:

An element is inserted, the number of nodes is n++, the element is inserted into the last position of the array, and then the key value of the inserted node is greater than the value of its parent node, and if greater than, the key value is exchanged with the parent node, and the value of its parent node is then recursively adjusted. Log (n) complexity

Reference code:

void Insert (int  key) {    n+ +;   The number of elements in the heap plus 1    a[n] = key;     int tmp_n = n;      while (tmp_n>1&&a[tmp_n]>a[tmp_n/2]) {        2]);         2 ;    }}

3: Heap top element throws:

After the heap top element is thrown, place the end element at the top of the heap and then make a head_adjust heap adjustment. Log (n) complexity

Reference code:

int pop () {    if1)return -1; // There are no elements    in the heap int MAXV = a[1];    Swap (a[1], a[n--]); // to interface with the heap ordering, the top element of the heap is swapped    with the last element of the heap 1 );     return MAXV;}

For the basic operations of the heap are given, the heap sort can be implemented simply. First, for an array of n unordered numbers, adjust to the heap, the process O (n) complexity. The heap top element is then constantly thrown, and the top element of the heap is exchanged with the heap tail element, iterating n times. Directly take advantage of the above-mentioned pop () operation.

Reference code:

int N // N is used to record the number of array elements void Heap_sort () {    for (int21; i--) Heap_adjust (a,i);      int t = n;     = N;      while (t--) {        pop ();    }}

Implementation and comparison of various types of sorting

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.