10 sort algorithms (code and description) and 10 sort Algorithms

Source: Internet
Author: User

10 sort algorithms (code and description) and 10 sort Algorithms

1. Bubble Sorting

The basic idea is to compare the key words of adjacent records in two or two pairs. If the reverse order is used, the key words are exchanged.

The best case of Bubble Sorting time complexity is O (n), and the worst case is O (n ^ 2)

Improvement Method 1: Set the flag bit. Obviously, if there is no switching (flag = false), the sorting is completed.

Improvement Concept 2: record the last position marked after a round. Next time, it will be OK from the header traversal to this position.

The original Bubble Sorting Code is as follows:

Void swap (int left, int right) {left = left ^ right; right = right ^ left; left = left ^ right ;} /*************************************** * *********************** // the case where the Bubble Sorting time is most complex is O (n ), the worst case is that O (n ^ 2) * The basic idea is: Compare the keywords of adjacent records in two or two pairs. If the reverse order is used, convert */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]) swap (arr [j], arr [j + 1]) ;}}
2. improvement ideas 1:
// Improvement train of thought: Set the flag bit. Obviously, if there is no switching (flag = flase), the sorting is completed. void swap (int left, int right) {left = 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. Improved thinking 2:

// Improvement idea: record the last position marked after a round. The next time you traverse from the header to this position, 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 ;}}}}



Ii. Insert directly to sort

Insert a record to an ordered table that has already been sorted to obtain a new ordered table with 1 Increase in the number of records

The time complexity is O (n ^ 2), which is better than bubble method and selection and sorting.

The Code is as follows:

/* Insert sorting: Insert a record to an ordered table that has already been sorted to obtain a new one, the time complexity of an ordered table with 1 Increase in the number of records is O (n ^ 2), which is better than the Bubble Method and the selected sorting method */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 ;}}

Iii. Simple selection and sorting

Through the comparison between the n-I keywords, select the record with the minimum keyword from the n-I + 1 record and the I (1 <= I <= n) records exchange

Although the same as the Bubble Sorting is O (n ^ 2), the performance of simple selection sorting is slightly better than that of Bubble sorting.

The Code is as follows:

/* Simple selection sort is to select the record with the smallest keyword from n-I + 1 * records by comparing the n-I keywords, and exchanged with records I (1 <= I <= n) * although the same as Bubble Sorting O (n ^ 2 ), however, the performance of simple sorting is slightly better than that of Bubble Sorting */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. Hill sorting

First, the entire sequence of elements to be sorted is divided into several sub-sequences (composed of elements separated by an increment) for direct insertion and sorting, and then the incremental sequence is reduced and then sorted, when the elements in the entire sequence are basically ordered (the increment is small enough), directly insert and sort all the elements (the increment is 1 ). The time complexity is O (n ^ 3/2), which is better than directly inserting the sorted O (n ^ 2)


<Span style = "font-size: 18px;">/</span> * Hill sorting: first, the entire sequence of elements to be sorted is divided into several sub-sequences (composed of elements separated by an increment) for direct insertion and sorting, and then the incremental sequence is reduced and then sorted, when the elements in the entire sequence are basically ordered (the increment is small enough), directly insert and sort all the elements (the increment is 1 ). The time complexity is O (n ^ 3/2), which is better than inserting the sorted 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 ;}}}

V. Merge Sorting

Assuming that the initial sequence contains n records, it can be considered as n ordered subsequences. The length of each subsequence is 1, and then the two are merged, we can obtain an ordered subsequence (minimum integer not less than n/2) with a length of 2 or 1, and then merge them in pairs ,... this is repeated until an ordered sequence with a length of n is obtained. This sorting method is called 2-way merge sorting. The time complexity is O (nlogn), and the space complexity is O (n + logn). If non-recursive merge is implemented, this avoids the complexity of the stack space with the logn depth in recursion as O (n ).

Code:


/* Assume that the initial sequence contains n records, then it can be considered as n ordered subsequences. The length of each subsequence is 1, and then * merge in two, we can obtain an ordered subsequence (minimum integer not less than n/2) with a length of 2 or 1, and then merge them in pairs ,... * This is repeated until an ordered sequence with a length of n is obtained. This sorting method is called 2-way Merge Sorting * the time complexity is O (nlogn ), the space complexity is O (n + logn). If non-recursive merge is implemented, the stack space with the depth of logn is avoided * The space complexity is O (n) * // * lpos is the start of left half, rpos is the start of right half */void merge (int a [], int tmp_array [], int lpos, int rpos, int rightn) {int I, leftn, num_elements, tmpos; leftn = rpos-1; tmpos = l Pos; num_elements = rightn-lpos + 1;/* main loop */while (lpos <= leftn & rpos <= rightn) if (a [lpos] <= a [rpos]) tmp_array [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 ");}


6. Heap sorting

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; or the value of each node is smaller than or equal to the value of its left and right child nodes.

/* 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. It is called a big top heap; * or the value of each node is smaller than or equal to the value of its left and right child nodes. It is called a small top heap * // * heap sorting is a method of sorting by heap. the basic idea is to construct the sequence to be sorted into a large top heap. at this time, the maximum value of the entire sequence is the root node of the heap top. remove it (in fact, it is to swap it with the end element of the heap array, at this time the end element is the maximum value), and then re-construct the n-1 sequences into a heap, in this way, the secondary operators of n elements are obtained. after repeated execution, an ordered sequence * // * is obtained. The time complexity is O (nlogn), which is better than bubble, simple choice, and directly inserted O (n ^ 2) * // construct a big top heap # define leftChild (I) (2 * (I) + 1) void percDown (int * arr, int I, int N) {int tmp, child; for (tmp = arr [I]; leftChil D (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 ;}

7. Counting sorting

Counting sort is a stable sorting algorithm. Count sorting uses an additional array C, where element I is the number of elements whose A value is equal to I in the array to be sorted. Then, sort the elements in A to the correct position based on Array C.

The algorithm steps are as follows:

  1. Find the largest and smallest elements in the array to be sorted
  2. Each value in the statistics array isINumber of times the element appears, saved to the arrayCTheIItem
  3. Accumulate all counts (fromCThe start of the element with the position of 1. Each item is added to the previous one)
  4. Reverse filling of the target array: add each elementIPlace the column in the New ArrayC (I)Item.C (I)Minus 1


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


******************** * **********/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; // apply for space and initialize it to 0 int * pCount = (int *) malloc (sizeof (int) * size); memset (pCount, 0, sizeof (int) * size); // records sorting count. Add 1 for (int I = 0; I <num; I ++) + pCount [arr [I]-mindata]; // you can specify the number of data records that are not greater than the specified position. for (int I = 1; I <size; I ++) pCount [I] + = pCount [I-1]; // Add the previous count int * pSort = (int *) malloc (sizeof (int) * num ); memset (char *) pSort, 0, sizeof (int) * num); // copy data from the end to repeat data first, that is, the stable sorting for (int I = num-1; I> = 0; I --) {// contains the need to subtract 1, when repeated data is returned, you also need to subtract 1 -- pCount [arr [I]-mindata]; pSort [pCount [arr [I]-mindata] = arr [I];} // copy to the original array for (int I = 0; I <num; I ++) arr [I] = pSort [I]; free (pCount ); free (pSort );}

8. Sort buckets

Bucket sorting (Bucket sort) or the so-called box sorting is a sorting algorithm. The working principle is to divide the array into a limited number of buckets. Sort each bucket individually (it is possible to use another sort algorithm or use the recursive method to continue sorting buckets)

Sort buckets by the following program:

  1. Set a quantitative array as an empty bucket.
  2. Search for the serial number, and place the items one by one in the corresponding bucket. (Hash)
  3. Sort buckets that are not empty.
  4. From a bucket that is not empty, put the project back into 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); // create each header node. The key of the header node stores the data size of the current bucket 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]); // save data for keys of other nodes // map function compute bucket ID // 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]-> key _) ++;} else {// locate the appropriate position to insert while (head-> next _! = NULL & head-> next _-> key _ <= ptr-> key _) head = head-> next _; ptr-> next _ = head-> next _; head-> next _ = ptr; (bucket_table [index]-> 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 --;} // release 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 ;}}}


9.Base sort

Base sorting (English: Radix sort) is a non-Comparative integer sorting algorithm. The principle is to cut an integer into different digits by the number of digits, and then compare them by the number of digits. Since integers can also express strings (such as names or dates) and floating point numbers in specific formats, the base sorting is not only applicable to integers.

It is implemented in this way: all the values to be compared (positive integers) are unified into the same digit length, and the number before the shorter digits is zero. Then, sort the data by bit. In this way, the sequence is changed to an ordered sequence after the ranking is completed until the sorting is completed by the highest bit.

The base sorting method can be LSD (Least significant digital) or MSD (Most significant digital). The LSD sorting method starts from the rightmost of the key value, while MSD is the opposite, start from the leftmost of the key value.

Void base_sort_ISD (int * arr, int num) {Node * buck [10]; // create a linked list array Node * tail [10]; // Save the pointer set of the End Node of each linked list. // when inserting the buck array, you do not need to traverse int I, MaxValue, kth, high, low; Node * ptr at the end of each link; 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 * 10, low <MaxValue; low * = 10) {// keep sorting as long as the order is not sorted for (I = 0; I <num; I ++) {// put kth = (arr [I] % high)/low in the bucket; // a bit of data is retrieved, index ptr = new Node (arr [I]) as the bucket; // create a new Node // connect to the 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 into the Array (the same linked list is from start 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 sorting

Set the array to be sorted to A [0]... A [N-1], first randomly select A data (usually the first number of the array) as the key data, and then put all the smaller than it before it, all the numbers larger than it are placed behind it. This process is called a fast sorting. It is worth noting that quick sorting is not a stable sorting algorithm, that is, the relative positions of multiple identical values may change at the end of the algorithm.

Void QuickSort (int a [], int numsize)/* a is an integer array, numsize is the number of elements */{int I = 0, j = numsize-1; int val = a [0];/* specify the val size of the reference value */if (numsize> 1)/* Ensure that the array length is at least 2, otherwise, you do not need to sort */{while (I <j)/* loop end condition */{/* to search for elements smaller than val from the back and forth, locate and fill in a [I] and jump out of the loop */for (; j> I; j --) if (a [j] <val) {a [I ++] = a [j]; break;}/* search for elements later than val, enter a [j] and jump out of the loop */for (; I <j; I ++) if (a [I]> val) {a [j --] = a [I]; break;} a [I] = val; /* put the number stored in val in a [I] */QuickSort (a, I);/* recursion, sort the number of front I */QuickSort (a + I + 1, numsize-i-1);/* sort the number of numsize-1-i from I + 2 to numsize */}}


Original address: Address



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.