The beauty of algorithms-Summary of sorting algorithms

Source: Internet
Author: User
Tags comparable

Simple comparison of sorting algorithms

1. Stability Comparison

Insertion sorting, Bubble sorting, binary tree sorting, two-way merge sorting, and other linear sorting are stable.

Selecting sorting (from the code point of view, there is a location replacement), Hill sorting, fast sorting, and heap sorting are unstable.

2. Comparison of time complexity

Insert sorting, Bubble sorting, and select the time complexity of sorting as O (n2)

The time complexity of other non-linear sorting is O (nlog2n)

The time complexity of Linear sorting is O (n );

3. Comparison of auxiliary space

The auxiliary space for Linear sorting and binary Merge Sorting is O (n), and the auxiliary space for other sorting is O (1 );

4. Other comparisons

The insertion and Bubble Sorting speed is slow, but this sorting speed can reach a high speed when the sequencing sequence is partial or overall.

In this case, fast sorting slows down.

When N is relatively small, sequence is not required for stability. sequence is required for stability. insertion or Bubble Sorting is required.

If the keywords of the record to be sorted are within a obviously limited range, and the space can be sorted in buckets.

When N is large, keyword elements are random, so quick sorting is not required for stability.

When N is large, the keyword element may appear in order. When stability is required, the space is allowed.

Sort by merge.

When N is large, the keyword element may appear in order, and there is no requirement for stability. sort by heap.

**************************************** **************************************** *****

Review the classic sorting idea-full solution of common sorting
/*
========================================================== ============================================
Introduction to relevant knowledge (all definitions are intended only to help readers understand related concepts, not strictly defined ):
1. Stable and non-stable sorting
Simply put, After all equal numbers are sorted by some sort method, they can still maintain their relative order before sorting.
This sorting method is stable. On the contrary, it is unstable.
For example, a group of numbers is sorted by A1, A2, A3, A4, and A5, where A2 is A4, Which is A1, A2, A4, A3, A5,
We can say that this sort is stable, because A2 is before A4, and it is still before A4. For example, A1, A4,
A2, A3, and A5 are not stable.

2. Inner and Outer sorting

In the sorting process, all the numbers to be sorted are in the memory and their storage order is adjusted in the memory;
In the sorting process, only part of the number is transferred to the memory, and the memory adjustment is used to store the number in the external storage. The sorting method is called external sorting.

3. Time and space complexity of the algorithm

The time complexity of an algorithm refers to the computing workload required to execute an algorithm.
The space complexity of an algorithm generally refers to the memory space required to execute this algorithm.

 

Time Complexity and space complexity

 

**************************************** ******************************

// Optimize quick sorting

**************************************** ******************************

 

Code:

Sort. h:

#ifndef SORT_H#define SORT_H#include <vector>#include "stdlib.h"using namespace std;namespace itlab{template<typename Type> void bubbleSort(vector<Type>&, int, int);template<typename Type> void selectSort(vector<Type>&, int, int);template<typename Type> void insertSort(vector<Type>&, int, int);template<typename Type> void quickSort(vector<Type>&, int, int);template<typename Type> void mergSort(vector<Type>&, int, int);template<typename Type> void heapSort(vector<Type>&, int, int);template<typename Type> const Type& median3(vector<Type>&, int, int);template<typename Type> void merg(vector<Type>&, int, int, int, int);template<typename Type> void filterDown(vector<Type>&, int, int);#include "Sort_impl.h"}#endif

Sort_impl.h

/*** Bubble sort algorithm. * "A" ----> array of comparable items. * "Left" ----> the left-most index of the subarray. * "right" ----> the right-most index of the subarray. */template <typename type> void bubblesort (vector <type> & A, int left, int right) {for (INT I = left; I <right; I ++) {// If the array is ordered and traversed once, sorted = true directly jumps out of the function; bool sorted = true; For (Int J = right; j> I; j --) {if (a [J] <A [J-1]) {swap (A [J], A [J-1]); sorted = false ;}} if (sorted) {return ;}}/ *** selection sort algorithm. * "A" ----> array of comparable items. * "Left" ----> the left-most index of the subarray. * "right" ----> the right-most index of the subarray. */template <typename type> void selectsort (vector <type> & A, int left, int right) {for (INT I = left; I <right; I ++) {int minpos = I; for (Int J = I + 1; j <right; j ++) {if (a [J] <A [minpos]) {Minpos = J ;}} if (I! = Minpos) {swap (A [I], a [minpos]) ;}}/ *** insertion sort algorithm. * "A" ----> array of comparable items. * "Left" ----> the left-most index of the subarray. * "right" ----> the right-most index of the subarray. */template <typename type> void insertsort (vector <type> & A, int left, int right) {for (INT I = left + 1; I <= right; I ++) // One insertion; {type TMP = A [I]; Int J; // For (j = I-1; j> = left & A [J]> TMP; j- -) // Insert a [I]; // {// A [J + 1] = A [J]; /// A [J + 1] = TMP; For (j = I; j> left & A [J-1]> TMP; j --) {A [J] = A [J-1];} A [J] = TMP;}/*** internal quicksort method that makes recursive CILS. * uses median-of-three partitioning and a cutoff of 20. * "A" ----> array of comparable items. * "Left" ----> the left-most index of the subarray. * "right" ----> the right-most index of the subarray. */template <typena Me type> void quicksort (vector <type> & A, int left, int right) {If (left + 20 <= right) {type align = median3 (A, left, right); // begin partitioningint I = left, j = right-1; for (;) {While (A [++ I] <cursor) {} while (iterator <A [-- J]) {} if (I <j) Swap (A [I], a [J]); elsebreak ;} // restore volume tswap (A [I], a [Right-1]); // The restore volume; region location is determined! In the next step, only two subsequences except a [I] are sorted. I must point to the first value greater than limit // sort small elementsquicksort (A, left, I-1); // sort large elementsquicksort (A, I + 1, right );} elseinsertsort (A, left, right);}/*** return median of left, center, and right. * order these and hide the same. */template <typename type> const type & median3 (vector <type> & A, int left, int right) {int center = (left + right)/2; // The sequence cannot be incorrect. If (A [left]> A [center]) {swap (A [left], a [center]);} I F (a [left]> A [right]) {swap (A [left], a [right]);} if (a [center]> A [right]) {swap (A [center], a [right]);} swap (A [center], a [Right-1]); /// // return a [Right-1];} /*** MERG sort algorithm (nonrecursion ). * "A" ----> array of comparable items. * "Left" ----> the left-most index of the subarray. * "right" ----> the right-most index of the subarray. */template <typename type> void mergs ORT (vector <type> & A, int left, int right) {int left1, right1, left2, Right2, n = right-left + 1, size = 1; while (size <n) {left1 = left; while (left1 + size <n) {left2 = left1 + size; right1 = left2-1; If (left2 + size> N) right2 = right; elseright2 = left2 + size-1; MERG (A, left1, right1, left2, Right2); left1 = Right2 + 1;} size * = 2 ;}} /*** MERG two subsequence to a bigger one. * The first subsequence is A [left1]... A [right1], and * The second subsqeuence is a [left2]... A [Right2]. */template <typename type> void MERG (vector <type> & A, int left1, int right1, int left2, int Right2) {int K = 0, I = left1, j = left2, n1 = right1-left1 + 1, n2 = right2-left2 + 1; type * TMP = new type [N1 + N2]; // start side by side while (I <= right1 & J <= Right2) if (a [I] <A [J]) TMP [k ++] = A [I ++]; else TMP [k ++] = A [J ++]; // after merging, there is a suborder. While (I <= right1) TMP [k ++] = A [I ++]; while (j <= Right2) TMP [k ++] = A [J ++]; // re-return the sequence for (INT I = 0; I <N1; ++ I) A [left1 ++] = TMP [I]; for (INT I = 0; I <N2; ++ I) A [left2 ++] = TMP [N1 + I]; Delete [] TMP ;}/ *** Heap Sort algorthm. * "A" ----> array of comparable items. * "Left" ----> the left-most index of the subarray. * "right" ----> the right-most index of the subarray. */template <typename typ E> void heapsort (vector <type> & A, int left, int right) {int n = right-left + 1; vector <type> TMP (N ); // assign value to TMP []; Sorting TMP []; for (INT I = 0; I <n; I ++) {TMP [I] = A [left + I];} // sort the node from the first node with children (n/2). // start from the bottom up, form a large root heap; For (INT I = n/2; I> = 0; I --) {filterdown (TMP, I, n);} // every cycle, swap the root and the end element; // then sort the root element from top to bottom to form a large heap again for (Int J = n-1; j> = 0; j --) {swap (TMP [0], TMP [J]); filterdown (TMP, 0, J);} // assign sorted Value To arrayfor (INT I = 0; I <n; I ++) {A [left + I] = TMP [I] ;}/ *** percolate down the heap. * "I" ----> the position from which to percolate down. * "N" ----> the logical size of the binary heap. */template <typename type> void filterdown (vector <type> & A, int I, int N) // A is the column to be sorted, and I is the position of a parent node, n is the number of elements in the column to be sorted; {int child; Type TMP; For (TMP = A [I]; 2 * I + 1 <n; I = Child) {Child = 2 * I + 1; if (child! = N-1 & A [child] <A [Child + 1]) {Child ++; // find the largest one in the child node} If (TMP <A [child]) {// A [I] = A [child]; swap (A [I], a [child]); // if the parent node is smaller than the child node, switch} elsebreak ;}}

Sort. cpp

C/C ++ generates random numbers.

/***************************************************************************** *                                sort_test.cpp * * Sorting algorithm testing. * * *****************************************************************************/#include <iostream>#include<stdlib.h>#include "sort.h"#include <random>using namespace std;using namespace itlab;#define random(x) (rand()%x)const int SIZE = 10;template <typename Type>void printVector( const vector<Type> &a ){    vector<int>::const_iterator itr = a.begin();    while( itr != a.end() )        cout << *itr++ << "\t";    cout << endl;}int main(){    vector<int> a( SIZE );    cout << "Unsorted Numbers : " << endl;for( unsigned i=0; i<a.size(); ++i )        a[i] = random(100);    printVector( a );    cout << "Bubble Sorted Numbers : " << endl;    bubbleSort( a, 0, a.size()-1 );    printVector( a );    cout << endl;    cout << "Unsorted Numbers : " << endl;    for( unsigned i=0; i<a.size(); ++i )        a[i] = random(100);    printVector( a );    cout << "Select Sorted Numbers : " << endl;    selectSort( a, 0, a.size()-1 );    printVector( a );    cout << endl;    cout << "Unsorted Numbers : " << endl;    for( unsigned i=0; i<a.size(); ++i )        a[i] = random(100);    printVector( a );    cout << "Insert Sorted Numbers : " << endl;    insertSort( a, 0, a.size()-1 );    printVector( a );    cout << endl;    cout << "Unsorted Numbers : " << endl;    for( unsigned i=0; i<a.size(); ++i )        a[i] = random(100);    printVector( a );    cout << "Quick Sorted Numbers : " << endl;    quickSort( a, 0, a.size()-1 );    printVector( a );    cout << endl;    cout << "Unsorted Numbers : " << endl;    for( unsigned i=0; i<a.size(); ++i )        a[i] = random(100);    printVector( a );    cout << "Merg Sorted Numbers : " << endl;    mergSort( a, 0, a.size()-1 );    printVector( a );    cout << endl;    cout << "Unsorted Numbers : " << endl;    for( unsigned i=0; i<a.size(); ++i )        a[i] = random(100);    printVector( a );    cout << "Heap Sorted Numbers : " << endl;    heapSort( a, 0, a.size()-1 );    printVector( a );    cout << endl;    return 0;}

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.