"Data structure" commonly used sorting algorithms (including: Select Sort, heap sort, bubble sort, select sort, quick sort, merge sort)

Source: Internet
Author: User
Tags assert

Direct Insert Sort:

In the sequence , assume ascending sort

1) start at 0.

1) If you go to begin = 3, save the Begin element to TMP, compare the element at TMP with the element size relationship at begin--, and move the begin-1 element to begin if it is <begin-1 at the beginning; Then the TMP is used to compare the elements of the begin--with the same method until begin is reduced to the end of the array starting at 0.

3) and so on, go through the sequence sequentially.


Complexity of Time: O ()

The code is as follows:

Sequence in ascending order void Insertsort (int* a,int size) {assert (a);        for (int begin = 0; begin < size; begin++) {int tmp = A[begin];        int end = Begin-1;            while (end >= 0 && tmp < A[end]) {a[end+1] = A[end];            A[end] = tmp;        end--; }    }}



2. Hill sort

The hill sort is actually the optimization and deformation of the direct insert sort. Assuming ascending sort

1) Let's go first to get an increment value gap, which divides the sequence into groups.

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/80/36/wKiom1c7GAOD1feJAAAvjnXLQpw626.png "title=" P3hn_ 3l1c[1) f{7v~}ugrxh.png "alt=" Wkiom1c7gaod1fejaaavjnxlqpw626.png "/>

2) Then we grouped to sort. When each grouping sort is sorted out, the order of the entire sequence is arranged.

3) Compare A[i],a[i+gap] size relationship, if A[I]>A[I+GAP], then swap. otherwise not processed. Go back and continue this step ...


The code is as follows:

Sequence in ascending order void shellsort (int* a, int size) {     assert (a);    int gap = size;     while  (gap > 1)     {        gap  = gap / 3 + 1;        for  (int  i = 0; i < size - gap; i++)          {            int end =  i;            int tmp = a[end  + gap];            while  (end &NBSP;&GT;=&NBSP;0&NBSP;&AMP;&AMP;&NBSP;A[END]&NBSP;&GT;&NBSP;A[END&NBSP;+&NBSP;GAP])              {                 a[end+gap] = a[end];                 a[end] = tmp;                 end -= gap;             }        }    }     }



3. Select sort

Assuming ascending sort

1) traverse the entire array for the 1th time, find the smallest (large) element, and place the element at the sequence 0 (size-1). At this point, the unordered sequence does not include 0 (size-1). For the 2nd time, the same method finds the smallest element in the remaining unsorted sequence, placed at 1.

2) Repeat until the end of the sequence, and the sequence is sorted.


Time complexity: O (n^2).


The code is as follows:

Sequence in ascending order void selectsort (int* a, int size) {     assert (a);        for  (int i = 0 ;  i < size; i++)     {         int minnum = i;        for  (int j  = i+1; j < size;j++)         {             if  (A[minnum] > a[j])              {                 minnum = j;             }                 }        if  (I != minnum)          {            swap (a[i], a[ Minnum]);        }             }}



4. Heap Sequencing

Assuming ascending sort

Let's think about ascending sequence, do we need to build a maximum heap or a minimum heap?

If the minimum heap, then the element of each root node is greater than the element of its child node. However, at this time there is no guarantee that her left and right node is greater than which, and can not guarantee the different layer of the node element size of the left and right subtree.

So, to design an ascending sort, we need to build a maximum heap.


1) Build a maximum heap.

2) for the 1th time, the element of the root node is exchanged with the last node element of the heap, so that the maximum element is guaranteed to be at the last node of the heap, and then the root node is not necessarily greater than the left and right child nodes, so it is adjusted downward to the appropriate position. For the 2nd time, the element of the root node is exchanged with the bottom 2nd node element of the heap, and the swapped root node is adjusted downward to the appropriate position ...


The code is as follows:

Void _adjustdown (int parent, int* a, int size) {    int  child = 2 * parent + 1;    while  (child <  Size)     {        if  (child + 1  < size && a[child + 1] > a[child])          {            child++ ;        }        if  (a[ Child] >a[parent])         {             swap (A[child], a[parent]);             parent = child;             child = 2 * parent + 1;        }         else        {             break;         }    }}//sequence in ascending order void heapsort (int*  a, int size) {    assert (a);    for  (int i  =  (size - 2)  / 2; i >= 0;i--)     {         _adjustdown (i, a, size);    }     for  (int i = 0; i < size -1; i++)      {        swap (a[0], a[size - i - 1]);        _adjustdown (0, a, size-i-1);     }} 



5. Bubble sort

Assuming ascending sort

Bubbling, as the name implies, slowly sinks like a bubble.

1) for the first time, compare a[0],a[1] size, if a[0]>a[1], then swap them. Compare a[1],a[2], if A[1]>A[2], then exchange ... Until the comparison a[size-1],a[size] ends, a maximum element has been sunk to the end of the sequence at size-1.

2) The second time, repeat the above operation, the largest element can sink to the size-2 place.

3) Repeat, complete the sorting.

Comparison:

Bubble sort is 22 comparison, which sinks the largest element at a time. Instead of selecting sort by, each traversal selects the largest element to be put to the last.


The code is as follows:

Sequence in ascending order void Bubblesort (int* a, int size) {assert (a); for (int i = 0, i < size; i++) {for (int j = 0; J < size-i-1, j + +) {if (A[j] > A            [j + 1])            {Swap (A[j], a[j + 1]); }        }    }}



6. Quick Sort

Quick sort, as the name implies, sorts the algorithm quickly and it is the quickest sort. The time complexity is: O (N*LGN). Suitable for chaotic sequences. Assuming ascending sort

For sequences: {5, 1,8,12, 19, 3, 7, 2, 4, 11}

1) We take the first data of the sequence as the comparison Datum, and set the position of the ordinal number 0 to be low, the position of the ordinal size-1 is high position.

2) Remove the datum element of the sequence key, at the moment of 5.

From right to left in the high position until you find an element that is smaller than the base value 5, which stops at element 4 at the moment.

Then, from left to right in the low position, until you find an element that is larger than the base value 5, the element 8 stops at the moment.

Because the datum element key is taken out at this point, the location where it is stored is empty. Assign the found element 4 to this position at the moment.

3) At this point the position of element 4 is empty, and the lower position of 8 will be found to be placed in this position.

4) Repeat this action, 2 to the base position, 12 to the original 2 position ...

5) Stop until Low>=high.


The above is a quick sort, after a quick sort, high and low meet each other to form an ordered sequence. Then the meeting position around each as a sequence, continue to do a quick sort, the final sequence can be sorted well.


The code is as follows:

Void quicksort (Int* a, int left,int right)  {    assert (a);     int low = left;    int high = right;     int key = a[low];    while  (low <  high)     {                         while  (Low < high  && key <= a[high])         {             high--;         }        a[low] = a[high];         while  (Low 


This article is from "Han Jing's Blog", please make sure to keep this source http://10740184.blog.51cto.com/10730184/1774508

"Data structure" commonly used sorting algorithms (including: Select Sort, heap sort, bubble sort, select sort, quick sort, merge sort)

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.