C ++ implementation and performance testing of various sorting algorithms

Source: Internet
Author: User

Sorting is a very important part of computer algorithms, and there are many implementation methods for sorting algorithms. Which sort algorithms are more efficient and which are more effective in specific scenarios, the following describes how to use C ++ to implement various algorithms and compare their efficiency. This gives us a deeper understanding of sorting.

Minheap. h is used for heap sorting:

// Add the key code # ifndef MINHEAP_H # define MINHEAP_H # include <assert. h ># include <iostream> using std: cout; using std: cin; using std: endl; using std: cerr; # include <stdlib. h> // const int maxPQSize = 50; template <class Type> class MinHeap {public: MinHeap (int maxSize); // create a MinHeap (Type arr [], int n); // create a heap according to the array arr ~ MinHeap () {delete [] heap;} const MinHeap <Type> & operator = (const MinHeap & R); // reload value assignment operator int Insert (const Type & x ); // Insert the element int RemoveMin (Type & x); // remove the element with the smallest key code and assign it to xint IsEmpty () const {return CurrentSize = 0 ;} // check whether the heap is empty int IsFull () const {return CurrentSize = MaxHeapSize;} // check whether the heap is full void MakeEmpty () {CurrentSize = 0 ;} // empty heap private: enum {DefaultSize = 50}; // default heap size Type * heap; Int CurrentSize; int MaxHeapSize; void FilterDown (int I, int m); // adjust the heap void FilterUp (int I) from top down; // adjust the heap from bottom up }; template <class Type> MinHeap <Type>: MinHeap (int maxSize) {// create a heap object MaxHeapSize = (DefaultSize <maxSize) based on the given maxSize )? MaxSize: DefaultSize; // determine the heap size. heap = new Type [MaxHeapSize]; // create the heap space CurrentSize = 0; // initialization} template <class Type> MinHeap <Type>:: MinHeap (Type arr [], int n) {// create a heap object MaxHeapSize = DefaultSize based on the data and size in the given array <n? N: DefaultSize; heap = new Type [MaxHeapSize]; if (heap = NULL) {cerr <"fail" <endl; exit (1 );} for (int I = 0; I <n; I ++) heap [I] = arr [I]; // The array transmits CurrentSize = n; // current heap size int currentPos = (CurrentSize-2)/2; // the last non-leaf while (currentPos> = 0) {// gradually expands from bottom to top, form heap FilterDown (currentPos, CurrentSize-1); currentPos --; // starting from currentPos, until 0, adjust currentPos -- ;}}template <class Type> void MinHeap <Type>:: FilterDo Wn (const int start, const int EndOfHeap) {// The left and right subtree of node I are heap. Adjust node iint I = start, j = 2 * I + 1; // j is the left child of I Type temp = heap [I]; while (j <= EndOfHeap) {if (j <EndOfHeap & heap [j]> heap [j + 1]) j ++; // if (temp <= heap [j]) break; else {heap [I] = heap [j]; I = j; j = 2 * j + 1 ;}} heap [I] = temp ;} template <class Type> int MinHeap <Type>: Insert (const Type & x) {// Insert a new element in the heap xif (CurrentSize = MaxHe ApSize) // full of {cout <"heap full" <endl; return 0;} heap [CurrentSize] = x; // Insert the FilterUp (CurrentSize) at the end of the table ); // adjust to the heap CurrentSize ++ up; // Add a return 1 to the heap element;} template <class Type> void MinHeap <Type >:: FilterUp (int start) {// from start, up until 0, adjust heap int j = start, I = (J-1)/2; // I is j's parent Type temp = heap [j]; while (j> 0) {if (heap [I]. root-> data. key) <= (temp. root-> data. key) break; else {heap [j] = heap [I]; j = I; I = (I-1)/2 ;}} heap [j] = temp;} template <class Type> int MinHeap <Type> :: removeMin (Type & x) {if (! CurrentSize) {cout <"heap empty" <endl; return 0;} x = heap [0]; // minimum element output queue heap [0] = heap [CurrentSize-1]; CurrentSize --; // fill FilterDown with the minimum element (0, CurrentSize-1 ); // change from top to bottom to heap return 1 from position 0;} # endif

The main sorting function sets of sort. cpp include Bubble sorting, fast sorting, insert sorting, Hill sorting, and count sorting:

// N ^ 2 // Bubble Sorting V [n] not involved in sorting void BubbleSort (int V [], int n) {bool exchange; // set the exchange flag to set for (int I = 0; I <n; I ++) {exchange = false; for (int j = n-1; j> I; j --) {// reverse detection, check for reverse order if (V [J-1]> V [j]) // Reverse Order occurs, swap adjacent elements {int temp = V [J-1]; V [J-1] = V [j]; V [j] = temp; exchange = true; // exchange flag placement} if (exchange = false) return; // This trip has no reverse order, stop processing} // insert sorting. L [begin] and L [end] all participate in the sorting void InsertionSort (int L [], const int begin, const int end ){// Sort the tables in non-descending order of Key code keys: int temp; int I, j; for (I = begin; I <end; I ++) {if (L [I]> L [I + 1]) {temp = L [I + 1]; j = I; do {L [j + 1] = L [j]; if (j = 0) {j --; break;} j --;} while (temp <L [j]); L [j + 1] = temp ;}}// n * logn // fast sort A [startingsub], A [endingsub] all participate in the sorting void QuickSort (int A [], int startingsub, int endingsub) {if (startingsub> = endingsub); else {int partition; int q = startingsub; int p = endingsub; int hold; do {for (partiti On = q; p> q; p --) {if (A [q]> A [p]) {hold = A [q]; A [q] = A [p]; A [p] = hold; break ;}}for (partition = p; p> q; q ++) {if (A [p] <A [q]) {hold = A [q]; A [q] = A [p]; A [p] = hold; break ;}}while (q <p); QuickSort (A, startingsub, partition-1); QuickSort (A, partition + 1, endingsub );}} // Hill sorting, L [left], L [right] are involved in sorting void Shellsort (int L [], const int left, const int right) {int I, j, gap = right-left + 1; // The initial incremental value in T temp; do {gap = gap/3 + 1; // calculate the next increment value for (I = left + gap; I <= right; I ++) // process the if (L [I] <L [I-gap]) for each sub-sequence in turn {// Reverse Order temp = L [I]; j = I-gap; do {L [j + gap] = L [j]; // The backward moving element j = j-gap; // compare the previous element} while (j> left & temp <L [j]); L [j + gap] = temp; // send vector [I] Back} while (gap> 1);} // n // sort the count, L [n] not involved in sorting void CountingSort (int L [], const int n) {int I, j; const int k = 1001; int tmp [k]; int * R; R = new int [n]; for (I = 0; I <k; I ++) tmp [I] = 0; for (j = 0; j <n; j ++) tmp [L [J] ++; // After the preceding loop is executed, the value of tmp [I] is the number of elements in the range of L to I for (I = 1; I <k; I ++) tmp [I] = tmp [I] + tmp [I-1]; // After the above loop is executed, // The tmp [I] value is the number of elements smaller than or equal to I in L for (j = n-1; j> = 0; j --) // here is reverse traversal, stability of sorting is ensured {R [tmp [L [j]-1] = L [j]; // L [j] is stored in the tmp [L [j] Location of the output array R. tmp [L [j] --; // tmp [L [j] indicates the number of elements remaining in L smaller than or equal to L [j]} for (j = 0; j <n; j ++) L [j] = R [j];} // The base sorting void printArray (const int Array [], const int arraySize); int getDigit (int num, int dig); const int radix = 10; // Base void RadixSort (int L [], int left, int right, int d) {// MSD Sorting Algorithm Implementation. Sort the sequence from high to low. D is the nth digit, and d = 1 is the second digit. Left and right are the start and end of the Child sequence of the elements to be sorted. Int I, j, count [radix], p1, p2; int * auxArray; int M = 5; auxArray = new int [right-left + 1]; if (d <= 0) return; // number of digits after processing recursion end if (right-left + 1 <M) {// for small sequences, you can directly Insert the InsertionSort (L, left, right); return ;}for (j = 0; j <radix; j ++) count [j] = 0; for (I = left; I <= right; I ++) // counts the storage location of each bucket element count [getDigit (L [I], d)] ++; for (j = 1; j <radix; j ++) // arrange the storage location of each bucket element count [j] = count [j] + count [J-1]; for (I = right; I> = left; I --){/ /Assign the elements in the sequence to each bucket by position and store them in the Help array auxArray j = getDigit (L [I], d ); // obtain the value of the d-bit of element L [I] auxArray [count [j]-1] = L [I]; // store count [j] --; // The counter minus 1} for (I = left, j = 0; I <= right; I ++, j ++) L [I] = auxArray [j]; // write the original array delete [] auxArray; for (j = 0; j <radix; j ++) {// recursive processing of D-1 BITs by bucket p1 = count [j] + left; // obtains the start and end of the bucket, relative position, initial Values $ $ (j + 1 <radix )? (P2 = count [j + 1]-1 + left) :( p2 = right); // obtain the end Of the bucket // delete [] count; if (p1 <p2) {RadixSort (L, p1, p2, D-1); // sort the base of elements in the bucket // printArray (L, 10) ;}} int getDigit (int num, int dig) {int myradix = 1;/* for (int I = 1; I <dig; I ++) {myradix * = radix;} */switch (dig) {case 1: myradix = 1; break; case 2: myradix = 10; break; case 3: myradix = 1000; break; case 4: myradix = 10000; break; default: myradix = 1; break;} return (num/myradix) % radix ;}

Maintest. cpp test example:

# Include <iostream> using std: cout; using std: cin; using std: endl; # include <cstdlib> # include <ctime> # include <iostream> using std: cout; using std: cin; using std: ios; using std: cerr; using std: endl; # include <iomanip> using std: setw; using std: fixed; # include <fstream> using std: ifstream; using std: ofstream; using std: flush; # include <string> using std: string; # include <stdio. h> # include <stdlib. h> # include <t Ime. h> # include "minheap. h "void BubbleSort (int arr [], int size); // bubble sort void QuickSort (int A [], int startingsub, int endingsub ); // fast sort void InsertionSort (int L [], const int begin, const int n); // insert sort void Shellsort (int L [], const int left, const int right); // Hill sorting void CountingSort (int L [], const int n); // count sorting int getDigit (int num, int dig ); // obtain the dig digit void RadixSort (int L [], int left, int right, Int d); // base sorting void printArray (const int Array [], const int arraySize); // output Array int main () {clock_t start, finish; double duration; /* measure the duration of an event */ofstream * ofs; string fileName = "sortResult.txt"; ofs = new ofstream (fileName. c_str (), ios: out | ios: app); const int size = 100000; int a [size]; int B [size]; srand (time (0); ofs-> close (); for (int I = 0; I <20; I ++) {ofs-> open (fileName. c_str (), ios: out | ios: app); if (Ofs-> fail () {cout <"!! "; Ofs-> close () ;}for (int k = 0; k <size; k ++) {a [k] = rand () % 1000; B [k] = a [k];}/* for (k = 0; k <size; k ++) {a [k] = k; B [k] = a [k];} * // printArray (a, size); // sort the count for (k = 0; k <size; k ++) {a [k] = B [k];} start = clock (); CountingSort (a, size); finish = clock (); // printArray (a, size ); duration = (double) (finish-start)/CLOCKS_PER_SEC; printf ("% s % f seconds \ n", "Count sorting:", duration ); * ofs <"no." <I <"Times: \ n" <"sorting content: 0 ~ 999 a total of "<size <" integers \ n "; * ofs <" no. "<I <" count sorting: \ n "<" Time: "<fixed <duration <" seconds \ n "; // base sorting for (k = 0; k <size; k ++) {a [k] = B [k];} start = clock (); RadixSort (a, 0, size-1, 3); finish = clock (); // printArray (a, size); duration = (double) (finish-start)/CLOCKS_PER_SEC; printf ("% s % f seconds \ n", "base sorting :", duration); * ofs <"no." <I <"times base sorting: \ n" <"Time:" <duration <"seconds \ n "; // heap sorting MinHeap <int> mhp (a, size); start = clock (); for (k = 0; k <size; k ++) {mhp. removeMin (a [k]);} finish = clock (); // printArray (a, size); duration = (double) (finish-start)/CLOCKS_PER_SEC; printf ("% s % f seconds \ n", "heap sorting:", duration); * ofs <"no" <I <"heap sorting: \ n "<" Time: "<duration <" seconds \ n "; // fast sorting for (k = 0; k <size; k ++) {a [k] = B [k];} // printArray (a, size); start = clock (); QuickSort (a, 0, size-1 ); finish = clock (); // printArray (a, size); duration = (double) (finish-start)/CLOCKS_PER_SEC; printf ("% s % f seconds \ n ", "quick sorting:", duration); * ofs <"no." <I <"secondary quick sorting: \ n" <"Time: "<duration <" seconds \ n "; // Hill sorting for (k = 0; k <size; k ++) {a [k] = B [k];} start = clock (); Shellsort (a, 0, size-1); finish = clock (); // printArray (a, size); duration = (double) (finish-start)/CLOCKS_PER_SEC; printf ("% s % f seconds \ n", "Hill sorting :", duration); * ofs <"no." <I <"secondary Hill sorting: \ n" <"Time:" <duration <"seconds \ n "; // Insert the sorting for (k = 0; k <size; k ++) {a [k] = B [k];} start = clock (); InsertionSort (, 0, size-1); finish = clock (); // printArray (a, size); duration = (double) (finish-start)/CLOCKS_PER_SEC; printf ("% s % f seconds \ n", "insert sorting:", duration); * ofs <"no" <I <"insert sorting: \ n "<" Time: "<duration <" seconds \ n "; // Bubble Sorting for (k = 0; k <size; k ++) {a [k] = B [k];} start = clock (); BubbleSort (a, size); finish = clock (); // printArray (a, size ); duration = (double) (finish-start)/CLOCKS_PER_SEC; printf ("% s % f seconds \ n", "bubble sort:", duration ); * ofs <"no" <I <"secondary Bubble Sorting: \ n" <"Time:" <duration <"seconds \ n "; ofs-> close ();} return 0;} void printArray (const int Array [], const int arraySize) {for (int I = 0; I <arraySize; I ++) {cout <Array [I] <""; if (I % 20 = 19) cout <endl ;}cout <endl ;}

Simulation of sorting algorithm performance:

Sorting content: from 0 ~ A total of 999 integers are randomly generated in 100000. The unit of this table is seconds.

Times Count sorting Base sort Heap sorting Quick sorting Hill sorting Insert sort directly Bubble Sorting
1 0.0000 0.0310 0.0470 0.0470 0.0310 14.7970 58.0930
2 0.0000 0.0470 0.0310 0.0470 0.0470 16.2500 53.3280
3 0.0000 0.0310 0.0310 0.0310 0.0310 14.4850 62.4380
4 0.0000 0.0320 0.0320 0.0470 0.0310 17.1090 61.8440
5 0.0000 0.0310 0.0470 0.0470 0.0310 16.9380 62.3280
6 0.0000 0.0310 0.0310 0.0470 0.0310 16.9380 57.7030
7 0.0000 0.0310 0.0470 0.0310 0.0310 16.8750 61.9380
8 0.0150 0.0470 0.0310 0.0470 0.0320 17.3910 62.8600
9 0.0000 0.0320 0.0470 0.0460 0.0310 16.9530 62.2660
10 0.0000 0.0470 0.0310 0.0470 0.0310 17.0160 60.1410
11 0.0000 0.0930 0.0780 0.0320 0.0310 14.6090 54.6570
12 0.0000 0.0310 0.0320 0.0310 0.0310 15.0940 62.3430
13 0.0000 0.0310 0.0310 0.0470 0.0310 17.2340 61.9530
14 0.0000 0.0320 0.0470 0.0470 0.0310 16.9060 61.0620
15 0.0000 0.0320 0.0320 0.0460 0.0320 16.7810 62.5310
16 0.0000 0.0470 0.0470 0.0620 0.0310 17.2350 57.1720
17 0.0150 0.0160 0.0320 0.0470 0.0310 14.1400 52.0320
18 0.0150 0.0160 0.0310 0.0310 0.0310 14.1100 52.3590
19 0.0000 0.0310 0.0320 0.0460 0.0320 14.1090 51.8750
20 0.0000 0.0310 0.0320 0.0460 0.0320 14.0780 52.4840
21 0.0150 0.0780 0.0470 0.0470 0.0310 16.3750 59.5150
22 0.0000 0.0310 0.0310 0.0470 0.0320 16.8900 60.3440
23 0.0000 0.0310 0.0310 0.0310 0.0310 16.3440 60.0930
24 0.0000 0.0310 0.0310 0.0470 0.0310 16.3440 60.5780
25 0.0000 0.0320 0.0470 0.0470 0.0470 16.3590 59.7810
26 0.0160 0.0470 0.0310 0.0470 0.0310 16.1250 61.0620
27 0.0000 0.0310 0.0470 0.0470 0.0310 16.7810 59.6100
28 0.0150 0.0320 0.0320 0.0470 0.0310 16.9220 56.8130
29 0.0000 0.0310 0.0310 0.0310 0.0310 15.0790 57.8120
30 0.0000 0.0310 0.0320 0.0460 0.0320 14.7810 58.8280
31 0.0000 0.0310 0.0310 0.0470 0.0310 15.8590 59.1400
32 0.0000 0.0470 0.0320 0.0310 0.0310 16.0940 59.1560
33 0.0000 0.0470 0.0310 0.0310 0.0310 15.9850 59.1400
34 0.0000 0.0310 0.0310 0.0470 0.0320 16.0150 59.2500
35 0.0000 0.0310 0.0470 0.0470 0.0310 16.7660 57.9840
36 0.0000 0.0310 0.0320 0.0470 0.0310 15.3750 59.0470
37 0.0000 0.0320 0.0460 0.0470 0.0320 16.0310 58.9060
38 0.0000 0.0310 0.0310 0.0470 0.0310 15.9530 57.2650
39 0.0160 0.0310 0.0470 0.0470 0.0310 15.9530 57.5160
40 0.0150 0.0310 0.0320 0.0470 0.0310 14.7030 56.6710
Average Value 0.0031 0.0360 0.0372 0.0437 0.0320 15.9946 58.7480
Minimum value 0.0000 0.0160 0.0310 0.0310 0.0310 14.0780 51.8750
Maximum Value 0.0160 0.0930 0.0780 0.0620 0.0470 17.3910 62.8600

Related Article

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.