Data Structure Learning Notes (ix)-Various sorting algorithms

Source: Internet
Author: User

A simple sort of 1. Bubble sort

The idea is to compare the next two elements each time, and if the latter one is smaller then the order of two elements is exchanged until the largest number is emitted (assuming small to large rows). Then we need to N-1 the order, each time the worst case Exchange N-1 times, the time complexity of two times.

2. Insert Sort

For those who like to play poker, we need to insert it into the right place after the grab, we need to compare it to the current hand one by one, until we find the smaller number (if it is from small to large rows). So for an array of int a[n], we need to sort N-1, from P=0 to p=n-1. Without inserting p, we need to compare it to the number of p+1 in front of it, assuming it is now the last, then compare it with the previous one next to it.

Here is the concept of a "reverse order pair", you can find that the insertion order every time the element is swapped, the number of reverse order is reduced once. You can launch:

Theorem: The time complexity of Ω (n^2) is required on average for any algorithm that is ordered by exchanging adjacent elements.

Ii. sort of Hill

In order to improve the efficiency of the algorithm, we should exchange several elements each time, so we have a hill sort. The idea is to sort through several elements at a time, with each order decreasing incrementally until the last interval is 1, which becomes the insertion sort.

But the time of the hill sort depends on the incremental selection.

Third, heap sorting

If we can use the structure of the smallest heap, each time we delete the root node, the smallest nodes leave first, and then they are stored in an array, but this method consumes extra storage.
The way to avoid using the second array is that the heap shrinks by 1 after the deletemin operation, so the unit at the end of the heap can be used to hold the element that was just deleted.

Iv. Merging and sorting

Using the idea of divide and conquer, divide and conquer first, then merge. The whole can be solved by recursion, which is similar to the addition of the previous two polynomial using the linked list. First the original array is divided into two, we also need to apply for a temporary array, set three counters, and then compare the smaller one to insert a temporary array. Finally, we can copy the temporary array back to the original array.

Five, code implementation
#include <cmath>#include <cstdio>#include <cstdlib>#include <iostream>#include <time.h>using namespace STD;typedef intElementType;voidInsertionsort (ElementType a[],intN) {/ * Insert sort * /  intP, I; ElementType Tmp; for(P =1; P < N; p++) {Tmp = a[p];/ * Remove the first element in the unordered sequence * /     for(i = P; i >0&& A[i-1] > Tmp; i--) A[i] = a[i-1];/* Compare and right-move the elements in the sorted sequence */A[i] = TMP;/ * Put in the right place * /}}voidShellSort0 (ElementType a[],intN) {intI, P, D, temp; for(D = N/2; D >0; D/=2) { for(P = D; P < N; p++) {temp = a[p]; for(i = P; I >= D && a[i-d] > temp; I-= D)      A[i] = a[i-d];    A[i] = temp; }  }}voidShellSort1 (ElementType a[],intN) {/* Hill sort-with sedgewick increment sequence */  intSi, D, P, I; ElementType Tmp;/ * Only a small portion of the increment is listed here * /  intSedgewick[] = {929,505,209,109, A, +,5,1,0}; for(Si =0; Sedgewick[si] >= N; si++);/ * Initial increment sedgewick[si] cannot exceed the length of the sequence to be ordered * /   for(D = Sedgewick[si]; D >0; D = Sedgewick[++si]) for(P = D; P < N; p++) {/ * Insert sort * /TMP = A[p]; for(i = P; I >= D && a[i-d] > Tmp; I-= D)      A[i] = a[i-d];    A[i] = TMP; }}voidSwap (ElementType *a, ElementType *b) {ElementType t = *a;  *a = *b; *b = t;}voidPercdown (ElementType a[],intPintN) {/* Percdown of the adapted code 4.24 (maxheap H, int p) */  / * Adjust the sub-heap of n elements in an array of a[p] to the maximum heap * /  intParent, child;  ElementType X; X = A[p];/ * Remove the value of the root node stored * /   for(Parent = p; (Parent *2+1) < N; Parent = child) {child = Parent *2+1;if((Child! = N-1) && (A[child] < A[child +1])) child++;/ * Child points to the larger of the left and right nodes * /    if(X >= A[child]) Break;/ * Find the right location * /    Else     / * Filter x * /A[parent] = A[child]; } A[parent] = X;}voidHeapsort (ElementType a[],intN) {/ * Heap sort * /  intI for(i = N/2-1; I >=0; i--)/ * Build Maximum heap * /Percdown (A, I, N); for(i = N-1; i >0; i--) {/ * Delete Maximum heap top * /Swap (&a[0], &a[i]);/ * See Code 7.1 * /Percdown (A,0, i); }}/* Merge sort-Recursive implementation *// * L = left start position, R = right start position, Rightend = right End position * /voidMerge (ElementType a[], ElementType tmpa[],intLintRintRightend) {/* Merge ordered A[l]~a[r-1] and A[r]~a[rightend] into an ordered sequence */  intLeftend, numelements, TMP;intI Leftend = R-1;/ * Left End position * /TMP = L;/ * Start position of ordered sequence * /numelements = Rightend-l +1; while(L <= leftend && R <= rightend) {if(A[l] <= a[r]) tmpa[tmp++] = a[l++];/ * Copy the Left element to Tmpa * /    Elsetmpa[tmp++] = a[r++];/ * Copy the right element to Tmpa * /} while(L <= Leftend) tmpa[tmp++] = a[l++];/ * Copy the left-hand side directly * /   while(R <= Rightend) tmpa[tmp++] = a[r++];/ * Copy the rest of the right side directly * *   for(i =0; i < numelements; i++, rightend--) a[rightend] = Tmpa[rightend];/ * Copy the ordered tmpa[] back to a[] * /}voidMsort (ElementType a[], ElementType tmpa[],intLintRightend) {/ * Core recursive sort function * /  intCenter;if(L < Rightend) {Center = (L + rightend)/2; Msort (A, Tmpa, L, Center);/ * Recursive resolution LEFT * /Msort (A, Tmpa, Center +1, rightend);/ * Resolve right by recursion * /Merge (A, Tmpa, L, Center +1, rightend);/ * Merge two sequential sequences * /}}voidMergeSort (ElementType a[],intN) {/ * Merge sort * /ElementType *tmpa; Tmpa = (ElementType *)mallocNsizeof(ElementType));if(Tmpa! = NULL) {Msort (A, Tmpa,0N1); Free(TMPA); }Else    printf("Not Enough space");}intMain () {ElementType a[100001], N; clock_t start, finish;Cin>> N; for(inti =0; i < N; i++)Cin>> A[i];  start = Clock ();  Insertionsort (A, N); finish = Clock ();DoubleDuration = (finish-start)/clocks_per_sec;//cout << "cost Time:" << duration << "s" << Endl;  cout<< a[0]; for(inti =1; i < N; i++)cout<<" "<< A[i];//cout << Endl;}
VI. Testing

Each test point data is as follows to compare the performance of various algorithms:

Data 1: only 1 elements;
Data 2:11 A different integer, test the basic correctness;
Data 3:103 random integers;
4:104 random integers of data;
5:105 random integers of data;
Data 6:105 sequential integers;
Data 7:105 inverse integers;
Data 8:105 basic ordered integers;
Data 9:105 random positive integers, not exceeding 1000 per digit.

Insert Sort:

Hill sort: (Increments of N/2)

Hill sort: (increment for Sedgewick increment sequence):

Heap Sort:

Merge sort:

You can see that heap sorting works best.

Data Structure Learning Notes (ix)-Various sorting algorithms

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.