Comparison of various sorting algorithms

Source: Internet
Author: User
Tags benchmark

1. Stability Comparison

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

It is unstable to select sorting, Hill sorting, fast sorting, and heap sorting.

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 in C Language

/*
========================================================== ============================================
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.
========================================================== ==========================================================
*/
/*
========================================================== ==========
Function: Select sorting
Input: array name (that is, the first address of the array), number of elements in the array
========================================================== ==========
*/
/*
========================================================== ================
A brief description of the algorithm concept:

In the number of groups to be sorted, the minimum number is selected to exchange with the number at the first position;
Then find the smallest number in the remaining number and exchange it with the number in the second position.
Until the second to last number is compared with the last number.

The sorting is unstable. Algorithm complexity O (n2) -- [the square of N]
========================================================== ==================
*/
Void select_sort (int * X, int N)
{
Int I, j, Min, T;

For (I = 0; I <n-1; I ++)/* Number of times to be selected: 0 ~ N-2 n-1 times */
{
Min = I;/* assume that the current subscript is the smallest number of I, and then adjust it after comparison */
For (j = I + 1; j <n; j ++)/* Find the subscript of the smallest number in a loop */
{
If (* (x + J) <* (x + min ))
{
Min = J;/* If the number is smaller than the previous one, write down its subscript */
}
}

If (Min! = I)/* If Min changes in the loop, data needs to be exchanged */
{
T = * (x + I );
* (X + I) = * (x + min );
* (X + min) = T;
}
}
}


/*
========================================================== ==========
Function: insert and sort data directly.
Input: array name (that is, the first address of the array), number of elements in the array
========================================================== ==========
*/
/*
========================================================== ================
A brief description of the algorithm concept:

In the number of groups to be sorted, assume that the number of the preceding (n-1) [n> = 2] is already
Now we need to insert the nth number into the previous ordered number so that the N number
It is also sorted. This repeats until all the rows are sorted.

Direct insertion and sorting are stable. Algorithm time complexity O (n2) -- [n square]
========================================================== ==================
*/
Void insert_sort (int * X, int N)
{
Int I, j, T;

For (I = 1; I <n; I ++)/* Number of times to be selected: 1 ~ N-1 total n-1 times */
{
/*
Number of saved subscript I. Note: The subscript starts from 1 because
The first number is the number of subscripts with 0. There is no number before.
It is ordered.
*/
T = * (x + I );
For (j = I-1; j> = 0 & T <* (x + J); j --)/* Note: J = I-1, j --, here is the number of Subscripts for I. There is a sequence before it to find the insert position. */
{
* (X + J + 1) = * (x + J);/* Move back if the conditions are met. The worst case is that t is smaller than the number of 0 subscripts. It should be placed at the beginning, j =-1, exit the loop */
}

* (X + J + 1) = T;/* locate the placement location of the number with the subscript I */
}
}


/*
========================================================== ==========
Function: Bubble Sorting
Input: array name (that is, the first address of the array), number of elements in the array
========================================================== ==========
*/
/*
========================================================== ================
A brief description of the algorithm concept:

In the number of groups to be sorted, the number of all numbers in the range not sorted yet, from the top
The next step is to compare and adjust the adjacent two numbers, so that a large number will sink
Small to go up. That is, when the number of two adjacent parties is compared, they are sorted and sorted.
On the contrary, they are exchanged.

The following is an improved bubble algorithm, which records the number of sinks after each scan.
Position K, which can reduce the number of times the outer loop scan is performed.

Bubble Sorting is stable. Algorithm time complexity O (n2) -- [n square]
========================================================== ==================
*/

Void bubble_sort (int * X, int N)
{
Int J, K, h, T;

For (H = n-1; h> 0; H = k)/* loop to no comparison range */
{
For (j = 0, K = 0; j {
If (* (x + J)> * (x + J + 1)/* put large values behind the scenes, and small values to the front */
{
T = * (x + J );
* (X + J) = * (x + J + 1 );
* (X + J + 1) = T;/* Complete switching */
K = J;/* Save the position of the last sink. In this way, K is sorted. */
}
}
}
}


/*
========================================================== ==========
Function: Hill sorting
Input: array name (that is, the first address of the array), number of elements in the array
========================================================== ==========
*/
/*
========================================================== ================
A brief description of the algorithm concept:

In the direct insertion sorting algorithm, insert a number at a time to add only one node to the sequence,
This does not help insert the next number. If the comparison is relatively long distance (called
Incremental), so that when the number moves across multiple elements, a comparison may be eliminated.
Multiple elements are exchanged. D. L. Shell was implemented in the sorting algorithm named by him in 1959.
This idea. The number of groups to be sorted by the algorithm is divided into several groups according to an incremental D.
The subscript of the record is different. D. Sort all the elements in each group, and then use a small increment.
Sort it and then sort it in each group. When the increment is reduced to 1, the entire number to be sorted is divided
A group. The sorting is complete.

The following function is an implementation of a hill sorting algorithm. The first half of the sequence is incremental,
It will be halved each time until the increment is 1.

Hill sorting is unstable.
========================================================== ==================
*/
Void shell_sort (int * X, int N)
{
Int H, J, K, T;

For (H = n/2; h> 0; H = H/2)/* control increment */
{
For (j = H; j <n; j ++)/* this is actually the sort of direct insertion above */
{
T = * (x + J );
For (k = J-H; (k> = 0 & T <* (x + k); k-= H)
{
* (X + K + H) = * (x + k );
}
* (X + K + H) = T;
}
}
}


/*
========================================================== ==========
Function: quick sorting
Input: array name (that is, the first address of the array), subscript of the starting and ending elements in the array
========================================================== ==========
*/
/*
========================================================== ================
A brief description of the algorithm concept:

Quick sorting is an essential improvement of Bubble sorting. Its basic idea is
After scanning, the length of the sorting sequence can be greatly reduced. In the Bubble sorting
Scanning can only ensure that the maximum number of values is moved to the correct position, while the length of the sequence to be sorted may only
Reduce by 1. A quick sorting scan ensures a certain number (based on it)
The numbers on the left are smaller than those on the right. And then process it in the same way.
The number of the left and right sides of it until there is only one element on the left and right of the benchmark. It is composed
C. A. R. Hoare proposed in 1962.

Obviously, quick sorting can be implemented using recursion, and of course stack-based recursive sorting can also be implemented. The following
Functions are implemented recursively. If you are interested, you can change them to non-recursive functions.

Fast sorting is unstable. Optimal Algorithm time complexity O (nlog2n) and Worst O (n2)

========================================================== ==================
*/
Void quick_sort (int * X, int low, int high)
{
Int I, j, T;

If (low {
I = low;
J = high;
T = * (x + low);/* Number of temporary points */

While (I <j)/* cyclic scan */
{
While (I <J & * (x + J)> T)/* If the value on the right is larger than the value on the reference point, it is still placed on the right */
{
J --;/* move a forward position */
}

If (I <j)
{
* (X + I) = * (x + J);/* loop exit above: A number smaller than the benchmark value. Replace the benchmark value */
I ++;/* move a position behind and use this as the benchmark */
}

While (I <J & * (x + I) <= T)/* on the left, as long as the value is less than or equal to the benchmark, it is still placed on the left */
{
I ++;/* move a location behind */
}

If (I <j)
{
* (X + J) = * (x + I);/* loop exit above: A number larger than the benchmark value. Put it on the right */
J --;/* move a forward position */
}
}

* (X + I) = T;/* after scanning, place it in the appropriate position */
Quick_sort (x, low, I-1);/* sort the number on the left of the reference point quickly */
Quick_sort (x, I + 1, high);/* sort the number on the right of the benchmark */
}
}


/*
========================================================== ==========
Function: heap sorting
Input: array name (that is, the first address of the array), number of elements in the array
========================================================== ==========
*/
/*
========================================================== ================
A brief description of the algorithm concept:

Heap sorting is a kind of tree-based sorting that effectively improves the Direct selection and sorting.
The heap is defined as follows: a sequence with n elements (H1, H2,..., HN ).
Meet (HI> = h2i, HI> = 2I + 1) or (Hi <= h2i, hi <= 2I + 1) (I = 1, 2 ,..., n/2)
It is called heap. Here we only discuss the heap that meets the conditions of the former.

From the definition of heap, we can see that the heap top element (that is, the first element) must be a heap top element. Full Binary Tree
Intuitively represents the heap structure. The heap top is the root, and the others are the left and right subtree.
Initially, the sequence of numbers to be sorted is regarded as a binary tree for sequential storage, and their storage order is adjusted,
Make it a heap, and the number of root nodes in the heap is the maximum. Then, the root node and the last node of the heap
Switch. Then adjust the preceding (n-1) number to make it heap. Wait until there are only two nodes.
And exchange them to obtain the ordered sequence of N nodes.

From the algorithm description, the heap sorting requires two processes: creating a heap and the last element of the heap top and heap.
Switch location. Therefore, heap sorting consists of two functions. One is the heap build penetration function, and the other is to call the penetration function repeatedly.
The sorting function.

Heap sorting is unstable. Algorithm time complexity O (nlog2n ).

*/
/*
Function: penetration heap
Input: array name (that is, the first address of the array), number of elements involved in heap creation, starting from the first element
*/
Void sift (int * X, int N, int S)
{
Int T, K, J;

T = * (x + S);/* Temporary Start Element */
K = s;/* Start Element subscript */
J = 2 * k + 1;/* element subscript of the right subtree */

While (j <n)
{
If (j <n-1 & * (x + J) <* (x + J + 1)/* determines whether the heap conditions are met: If yes, continue the next round of comparison, otherwise, adjust. */
{
J ++;
}

If (T <* (x + J)/* adjust */
{
* (X + k) = * (x + J );
K = J;/* after adjustment, the start element is also adjusted */
J = 2 * k + 1;
}
Else/* does not need to be adjusted. It is already a heap and exits the loop. */
{
Break;
}
}

* (X + k) = T;/* place the Start Element in the correct position */
}


/*
Function: heap sorting
Input: array name (that is, the first address of the array), number of elements in the array
*/
Void heap_sort (int * X, int N)
{
Int I, K, T;
Int * P;

For (I = n/2-1; I> = 0; I --)
{
Sift (x, N, I);/* Initial heap creation */
}

For (k = n-1; k> = 1; k --)
{
T = * (x + 0);/* place the heap top to the end */
* (X + 0) = * (x + k );
* (X + k) = T;
Sift (x, K, 0);/* Create a heap after the remaining number */
}
}


Void main ()
{
# Define max 4
Int * P, I, a [Max];

/* Enter Test Data */
P =;
Printf ("input % d number for sorting:/N", max );
For (I = 0; I <Max; I ++)
{
Scanf ("% d", P ++ );
}
Printf ("/N ");

/* Select sorting for test */


P =;
Select_sort (p, max );
/**/


/* Insert sorting directly in the test */

/*
P =;
Insert_sort (p, max );
*/


/* Test the Bubble Sorting */

/*
P =;
Insert_sort (p, max );
*/

/* Test quick sorting */

/*
P =;
Quick_sort (p, 0, MAX-1 );
*/

/* Test heap sorting */

/*
P =;
Heap_sort (p, max );
*/

For (P = A, I = 0; I <Max; I ++)
{
Printf ("% d", * P ++ );
}

Printf ("/N ");
System ("pause ");
}

 

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.