Summary of 10 sorting algorithms (Code and description)

Source: Internet
Author: User

1. Bubble sort

The basic idea is: 22 compare the keywords of adjacent records, if the reverse order is exchanged

The best case for bubble sort time complexity is O (n), and the worst case is O (n^2)

Improvement Idea 1: Set the flag bit, obviously if there is a trip without exchange (flag = false), indicating that the sort has been completed

Improvement Idea 2: Record the last position of the marker, and the next step from the head to this position is OK.

The original bubbling sort code is as follows:

void swap (int left, int. right) {    Left  = left ^ right;    right = right ^ left;    Left  = left ^ right;} /*****************************************************************//* Bubble Sort Time complexity best case for O (n), worst case is O (n^2) * Basic idea is: 22 Compare the keywords of adjacent records, if the reverse order is exchanged */void bubblesort (int arr[], int num) {    int i, J;    for (i = 0, i < num; i++)    {for        (j = 1; J < num-i-1, j + +)        {            if (Arr[j] > arr[j + 1])                SW AP (Arr[j], arr[j + 1]);}}}    
2. Ideas for improvement 1:
Improved thinking: Set the flag bit, obviously if there was a trip without an exchange (flag = flase), the description sort has been completed. void swap (int left, int right) {leaving  = left ^ right;    right = right ^ left;    Left  = left ^ right;} void Bubblesort (int arr[], int num) {    int k = num;    Int J;    BOOL flag = TRUE;    while (flag)    {        flag = false;        for (j = 1; j < K; J + +)        {            if (Arr[j] > arr[j + 1])            {                swap1 (arr[j], arr[j + 1]);                Flag = true;            }        }        k--;}    }

3. Ideas for Improvement 2:

Improved thinking: Record the last position of the mark at the end of the cycle, and the next step from the head to this position is okvoid BubbleSort3 (int arr[], int num) {    int k, J;    int flag = num;    while (Flag > 0)    {        k = flag;        Flag = 0;        for (j = 1; j < K; J + +)        {            if (Arr[j] > arr[j + 1])            {                swap1 (arr[j], arr[j + 1]);                Flag = J;}}}    



Two. Direct Insert sort

Insert a record into an ordered table that is already sorted to get a new, sequential table with a 1 increase in record count

The time complexity is also O (n^2), which is better than the bubbling method and the choice of sorting performance.

The code is as follows:

/* Insert sort: Insert a record into an ordered table that is already sorted to get a new, sequential table with a record count of 1 * Time complexity is also O (n^2), better than bubble method and select Sort performance. */void insertionsort (int arr[], int num) {    int temp;    int I, J;    for (i = 1; i < num; i++)    {        temp = arr[i];        for (j = i; j > 0 && arr[j-1] > temp; j--)            arr[j] = arr[j-1];        ARR[J] = temp;    }}

Three, simple selection of sorting

By n-i The comparison between the sub-keywords, select the smallest record of the keyword from the n-i+1 record and exchange the record with the first (1<=i<=n)

Although the same as O (n^2) with bubble sort, the performance of simple selection sorting is slightly better than the bubble sort

The code is as follows:

/* Simple Select sort (Easy selection sort) is to select the smallest record of the keyword from the n-i+1* record by comparing the n-i with the second keyword, and the 1<=i<=n record Exchange * Although with the bubble sort is O (n^2),    But simple selection of the performance of the sort is slightly better than the bubble sort */void swap (int left, int right) {left = left ^ right;    right = right ^ left; left = left ^ right;} <span style= "color: #8000ff;" >void</span> selectsort (<span style= "color: #8000ff;" >int</span> arr[], <span style= "color: #8000ff;" >int</span> num) {    <span style= "color: #8000ff;" >int</span> i, j, mindex;    <span style= "color: #0000ff;" >for</span>  (I = <span style= "color: #ff0000;" >0</span>; i < num; i++)     {         mindex = i;        <span style= " Color: #0000ff; " >for</span>  (J = i + <span style= "color: #ff0000;" >1</span>; j < num; j++)         {             <span style= "color: #0000ff;" >if</span>  (Arr[j] < arr[mindex])                  Mindex = j;         }        swap1 (&arr[i], &arr[mindex]);     }}

Iv. sort of Hill

The entire sequence of elements to be sorted into a number of sub-sequences (composed of elements separated by an "increment") is directly inserted into the sort, and then reduced incrementally and then sorted, and then the entire sequence of elements is basically ordered (the increment is small enough), and then the whole element of a direct insert sort (increment 1). Its time complexity is O (N^3/2), better than direct insertion of the sort O (n^2)


<span style= "FONT-SIZE:18PX;" >/</span>*: First, the entire sequence of elements to be sorted into sub-sequences (consisting of an element separated by an "increment") is directly inserted into the sort, and then reduced incrementally and then sorted, and the elements in the whole sequence are basically ordered (the increments are small enough). A direct insert sort (increment of 1) is then performed on the entire element. Its time complexity is O (N^3/2), better than the direct insertion sort O (n^2) */void shellsort (int *arr, int n) {    int i, j, increment;    int tmp;    for (increment = N/2; increment > 0, Increment/= 2)    {for        (i = increment; i < N; i++)        {            tmp = arr [i];            for (j = i; J >= increment; J-= increment)            {                if (Arr[j-increment] > tmp)                    arr[j] = arr[j-increment] ;                else break                    ;            }            ARR[J] = tmp;}}    }

Five, merge sort

Assuming that the initial sequence contains n records, it can be regarded as N ordered subsequence, each subsequence length is 1, and then 22 merges, to get (the smallest integer not less than N/2) of 2 or 1 of the ordered subsequence, and then 22 merge,... So repeat until you get an ordered sequence of length n, which is called a 2-way merge sort. The time complexity is O (NLOGN), the space complexity is O (N+LOGN), if the non-recursive implementation of the merge, it avoids the recursive time depth of Logn stack space complexity of O (n).

Code:


/* Assuming that the initial sequence contains n records, it can be regarded as N ordered subsequence, each subsequence length is 1, and then * 22 is merged, to get (the smallest integer not less than N/2) the ordered subsequence of length 2 or 1, and then 22 merge,... * So repeat until an ordered sequence of length n is reached. This sort method is called 2-way Merge sort * Time complexity is O (NLOGN), spatial complexity is O (N+LOGN), if the non-recursive implementation of the merge, it avoids the recursive time depth of Logn stack space * space complexity of O (n) *//*lpos is the start of the left Half, RpoS is the start of right half*/void merge (int a[], int tmp_array[], int lpos, int rpos, int rightn) {int I, lef    TN, num_elements, Tmpos;    leftn = rpos-1;    Tmpos = Lpos;    num_elements = Rightn-lpos + 1; /*main loop*/while (lpos <= leftn && rpos <= rightn) if (A[lpos] <= A[rpos]) Tmp_ar        ray[tmpos++] = a[lpos++];    else tmp_array[tmpos++] = a[rpos++];    while (Lpos <= leftn)/*copy Rest of the first part*/tmp_array[tmpos++] = a[lpos++];    while (RpoS <= rightn)/*copy Rest of the second part*/tmp_array[tmpos++] = a[rpos++]; /*copy array back*/for (i = 0; i < num_elements; i++, rightn--) a[rightn] = Tmp_array[rightn];} void Msort (int a[], int tmp_array[], int left, int right) {int center;        if (left < right) {Center = (right + left)/2;        Msort (A, Tmp_array, left, center);        Msort (A, Tmp_array, center + 1, right);    Merge (A, Tmp_array, left, center + 1, right);    }}void merge_sort (int a[], int n) {int *tmp_array;    Tmp_array = (int *) malloc (n * sizeof (int));        if (tmp_array! = NULL) {Msort (A, Tmp_array, 0, n-1);    Free (Tmp_array); } else printf ("No Space for TMP array!\n");}


vi. sequencing of heaps

A heap is a complete binary tree with the following properties: The value of each node is greater than or equal to the value of its left and right child nodes, called the Big Top heap, or the value of each node is less than or equal to the value of its left and right child nodes, called the small top heap.

/* Heap is a complete binary tree with the following properties: Each node's value is greater than or equal to the value of its left and right child nodes, called the Big Top heap; * or the value of each node is less than or equal to the value of its left and right child nodes, called the small top heap *//* heap ordering is the method of using the heap to sort. Constructs the sequence to be sorted into a large top heap. At this point, the maximum value of the entire sequence is the root node of the heap top *. Remove it (in fact, swap it with the end element of the heap array, at which point the element at the end is the maximum value), and then re-construct the remaining n-1 sequence into a heap. This gives you a secondary value of n elements. So repeated execution, you can get an ordered sequence of *//* time complexity of O (NLOGN), better than bubbling, simple selection, directly inserted O (n^2) *///structure large Top heap # define LEFTCHILD (i) ((i) + 1)    void Percdown (int *arr, int i, int N) {int TMP, child;        for (TMP = Arr[i], leftchild (i) < N; i = child) {child = Leftchild (i);        if (Child! = N-1 && arr[child + 1] > Arr[child]) child++;        if (Arr[child] > tmp) arr[i] = Arr[child];    else break; } Arr[i] = tmp;}    void Heapsort (int *arr, int N) {int i;    for (i = N/2; I >= 0; i--) percdown (arr, I, N);        for (i = N-1; i > 0; i--) {Swap1 (&arr[0], &arr[i]);    Percdown (arr, 0, I);    }}int Main (void) {int arr[] = {9, 2, 5, 8, 3, 4, 7, 1, 6, 10};    Heapsort (arr, 10); for (int i = 0; i <10;    i++) cout << arr[i] << ";    cout << Endl; return 0;}

Seven: Counting sort

Count sort (counting sort) is a stable Sorting Algorithms . The count sort uses an extra array of C, where the I element is the number of elements in the array A to be sorted with the value equal to I. The elements in a are then ranked in the correct position according to the array C.

The steps of the algorithm are as follows:

    1. Find the largest and smallest elements in the array to be sorted
    2. Count the number of occurrences of each element in the array of I , stored in the item i of array C
    3. Sum of all counts (starting with elements from position 1 in C , adding each item to the previous item)
    4. Reverse-Populate the target array: Place each element I in the C (i) of the new array, subtract C (i) by 1 for each element placed


Because the array used to countClength depends on the range of data in the array to be sorted (equal to the difference between the maximum and minimum values of the array to be sorted plus 1), which makes the count sort for arrays with a large data range, which requires a lot of time and memory


/***************** count sort *******************************/void countsort (int *arr, int num) {int mindata = arr[0];    int maxdata = arr[0];        for (int i = 1; i < num; i++) {if (Arr[i] > Maxdata) maxdata = Arr[i];    if (Arr[i] < Mindata) Mindata = Arr[i];    } int size = Maxdata-mindata + 1;    Request space and initialize to 0 int *pcount = (int *) malloc (sizeof (int) * size);    memset (pcount, 0, sizeof (int) *size);    Record sort count, each occurrence at corresponding position plus 1 for (int i = 0; i < num; i++) ++pcount[arr[i]-mindata]; Determine the number of data not larger than the location for (int i = 1; i < size; i++) pcount[i] + = pcount[i-1];    Plus the previous count int *psort = (int *) malloc (sizeof (int) * num);    memset ((char*) psort, 0, sizeof (int) * num); Copying from the end is for the first occurrence of repeating data, that is, the stable sort for (int i = num-1; I >= 0; i--) {//contains itself need to reduce 1, repeat data loop back also need to reduce 1--pco        Unt[arr[i]-mindata];    Psort[pcount[arr[i]-mindata]] = arr[i];     }//Copy to original array for (int i = 0; i < num; i++)   Arr[i] = Psort[i];    Free (pcount); Free (psort);}

Eight: Bucket sort

bucket sort (Bucket sort) or the so-called box sort is a sorting algorithm sorting algorithm or recursively continue to sort by using the bucket sort)

The buckets are sorted by the following procedure:

    1. Sets a quantitative array as an empty bucket.
    2. Search the serial, and put the project one to the corresponding bucket. (hash)
    3. Sorts each bucket that is not empty.
    4. From a bucket that is not empty, put the item back in the original serial.

struct node{int key_;    struct Node *next_;        Node (int key) {key_ = key;    Next_ = NULL;    }}; #define Bucket_size 10//equal to the number of array elements void Buck_sort (int arr[], int num) {Node *bucket_table[bucket_size];    memset (bucket_table, 0, sizeof (bucket_table));        Build each head node, key of the head node to save the current bucket's data volume for (int i = 0; i < bucket_size; i++) bucket_table[i] = new Node (0);    int maxValue = arr[0];    for (int i = 1; i < num; i++) {if (Arr[i] > MaxValue) maxValue = Arr[i]; } for (int j = 0; j < Num; J + +) {node *ptr = new node (arr[j]);//Key of the remaining node save data//Map function Calculate bucket number//        Index = (value * number_of_elements)/(MaxValue + 1) int index = (arr[j] * bucket_size)/(MaxValue + 1);        Node *head = Bucket_table[index];            The bucket has no data if (Head->key_ = = 0) {bucket_table[index]->next_ = ptr;        (BUCKET_TABLE[INDEX]-&GT;KEY_) + +; } else {//find a suitable locationInsert while (head->next_! = NULL && head->next_->key_ <= ptr->key_) head = h            ead->next_;            Ptr->next_ = head->next_;            Head->next_ = ptr;        (BUCKET_TABLE[INDEX]-&GT;KEY_) + +;    }}//Copy the data in the bucket back to the original array int m, n;  for (m = 0, n = 0; n < num && m < bucket_size;        m++, n++) {Node *ptr = bucket_table[m]->next_;            while (ptr! = NULL) {Arr[n] = ptr->key_;            PTR = ptr->next_;        n++;    } n--;        }//Releases the allocated dynamic space for (m = 0; m < bucket_size; m++) {Node *ptr = bucket_table[m];        Node *tmp = NULL;            while (ptr! = NULL) {tmp = ptr->next_;            Delete ptr;        PTR = tmp; }    }}


Nine. base Sorting

Base Sort ( English:Radix sort ) is a non-comparative integer sorting algorithm , which is based on cutting the number of digits into different numbers and then comparing them by the number of bits. Because integers can also express strings (such as names or dates) and floating-point numbers in a particular format, the cardinality sort is not only used for integers.

It does this by unifying all the values to be compared (positive integers) to the same digit length, which is preceded by a short number of digits of 0. Then, start with the lowest bit and order one at a time. Thus, from the lowest bit to the highest order, the sequence becomes an ordered series.

The cardinality is sorted by LSD (Least significant digital) or MSD (most significant digital), and LSD is sorted by the rightmost start of the key value, while the MSD is the opposite, starting with the leftmost side of the key value.

void BASE_SORT_ISD (int *arr, int num) {node *buck[10];//Create a list of linked arrays node *tail[10];//save each linked footer node pointer collection,//To insert the buck array    It is not necessary to iterate to the end of int i, MaxValue, KTH, high and low every time;    Node *ptr;    for (MaxValue = arr[0], i = 1; i < num; i++) MaxValue = max (MaxValue, Arr[i]);    memset (Buck, 0, sizeof (Buck));    memset (tail, 0, sizeof (Buck));        for (low = 1; high = low * Ten, Low < MaxValue; *= 10) {//The order is sorted for (i = 0; i < num; i++) as long as the order is not queued {//Put kth = (Arr[i]% high)/low;//take out one of the data, as the index of the bucket ptr = new Node (arr[i]);//Create                New node//Receive End if (buck[kth]! = NULL) {tail[kth]->next_ = ptr;            TAIL[KTH] = ptr;                } else {buck[kth] = ptr;            TAIL[KTH] = ptr; }}//Put the data in the bucket back into the array (the same chain list is from beginning to end) for (kth = 0, i = 0; kth < num; i++) {while (buck[    I]! = NULL) {            arr[kth++] = buck[i]->key_;                ptr = Buck[i];                Buck[i] = buck[i]->next_;            Delete ptr;    }} memset (tail, 0, sizeof (Buck)); }}

10. Quick Sort



Original address: Address



Summary of 10 sorting algorithms (Code and description)

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.