Summary of common sorting algorithms. __ algorithm

Source: Internet
Author: User
Tags comparison min printf
Related knowledge (all definitions are intended to help readers understand concepts, not strictly defined):
1, stable sort and unstable sort
Simply put, all equal numbers, after some sort of sorting method, can still keep their relative order before they are sorted, we
Say this sort of method is stable. On the contrary, it is not stable.
For example: A group of numbers before the order is A1,A2,A3,A4,A5, which a2=a4, after some sort of a1,a2,a4,a3,a5,
Then we say that this sort is stable, since the A2 is sorted before the A4, sorted before it is in front of A4. If it becomes a1,a4,
The A2,A3,A5 is not stable. 2, internal sorting and outside sorting
In the sort process, all the numbers that need to be sorted are in memory and the order of their storage is adjusted in memory, called inner ordering;
In the sort process, only a portion of the number is transferred into memory, with the help of the memory adjustment number in the stored order ordering method called the outer sort.

3, the time complexity of the algorithm and the complexity of space

The time complexity of the so-called algorithm refers to the computational work required to perform the algorithm.
The spatial complexity of an algorithm generally refers to the memory space needed to execute this algorithm.
================================================================================
*/


/*
================================================
Features: selecting sort
Input: Array name (that is, array first address), the number of elements in the array
================================================
*/
/*
====================================================
Algorithm idea Simple description:

In the set of numbers to be sorted, select the smallest number to exchange with the number of the first position;
And then find the smallest number in the remaining number to exchange with the second position, so that the loop
To the penultimate number and the last number of comparisons.

The select sort is not stable. Algorithm complexity O (n2)--[n squared]
=====================================================
*/
void Select_sort (int *x, int n)
{
int I, J, Min, T;

For (i=0 i<n-1; i++)/* Number of times to select: 0~n-2 n-1 times * *
{
min = i; /* Assume that the number of subscript i is the smallest, and then adjust after comparison.
For (j=i+1 j<n; j + +)/* loop to find out which subscript is the smallest number.
{
if (* (X+J) < * (x+min))
{
min = j; * * If the number of the following is smaller than the front, note its subscript * * *
}
}

if (min!= i)/* If min changes in the loop, you need to exchange the data * *
{
t = * (x+i);
* (x+i) = * (X+min);
* (x+min) = t;
}
}
}


/*
================================================
Function: Direct Insert sort
Input: Array name (that is, array first address), the number of elements in the array
================================================
*/
/*
====================================================
Algorithm idea Simple description:

In the set of numbers to sort, suppose that the front (n-1) [n>=2] number is already a row
In a good order, now you have to insert the nth number into the preceding ordered number so that the number of n
It's a good order, too. Repeat the loop until all the order is sorted.

The direct insert sort is stable. Algorithm time complexity O (n2)--[n squared]
=====================================================
*/
void Insert_sort (int *x, int n)
{
int I, j, T;

For (I=1 i<n; i++)/* Number of times to select: 1~n-1 n-1 times * *
{
/*
The number of staging subscript i. Note: The subscript starts at 1 because it starts
The first number is the number of subscript 0, the front without any number, alone, that
It's in the right order.
*/
t=* (X+i);
For (j=i-1 j>=0 && t<* (x+j); j--)/* Note: j=i-1,j--, here is the number of subscript I, which is preceded by a sequence in which to find the insertion position. */
{
* (x+j+1) = * (X+J); * * If the conditions are met, move back. The worst case scenario is that T is smaller than the number 0, it's going to be at the front, j==-1, exiting the loop.
}

* (x+j+1) = t; /* Find the placement position of the number subscript I
}
}


/*
================================================
Features: Bubble sort
Input: Array name (that is, array first address), the number of elements in the array
================================================
*/
/*
====================================================
Algorithm idea Simple description:

In the number of groups to sort, the total number of the ranges that are not yet sorted, from the
The next two consecutive numbers are compared and adjusted in turn, so that the larger number to sink, more
Small to go up. That is: whenever two adjacent numbers are compared, they are found to be sorted and sorted
When you ask for the opposite, swap them.

Here is an improved bubbling algorithm that records the last sinking number after each scan.
Position k, which reduces the number of times the outer loop scan is available.

The bubble sort is stable. Algorithm time complexity O (n2)--[n squared]
=====================================================
*/

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))/* Large on the back, small put in front * *
{
t = * (X+J);
* (X+J) = * (x+j+1);
* (x+j+1) = t; /* Complete the exchange * *
K = J; /* Save the last sinking position. So the k behind are sorted out of the line. */
}
}
}
}


/*
================================================
Function: Hill sort
Input: Array name (that is, array first address), the number of elements in the array
================================================
*/
/*
====================================================
Algorithm idea Simple description:

In the direct insert sort algorithm, each time a number is inserted, the ordered sequence is incremented by only 1 nodes.
And does not provide any help for inserting the next number. If you compare the distance between the more distant (called
Increment), which allows multiple elements to span when the number is moved, a comparison may eliminate
Multiple element Exchange. D.l.shell was implemented in 1959 in a sorting algorithm named after his name.
The idea. The algorithm first sets the number of groups to be sorted into groups by an increment d, in each group
Record subscript difference D. Sort all the elements in each group, and then use a smaller increment
Do it, and then sort it in each group. When the increment is reduced to 1 o'clock, the entire number to be sorted is divided into
A set of sorted finishes.

The following function is an implementation of a hill sort algorithm, with half of the initial sequence being incremental,
Halve each time until the increment is 1.

Hill sort is not stable.
=====================================================
*/
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 direct insert sort above
{
t = * (X+J);
for (k=j-h; (K>=0 && t<* (x+k)); K-=H)
{
* (X+K+H) = * (X+K);
}
* (x+k+h) = t;
}
}
}


/*
================================================
Features: Quick Sort
Input: Array name (that is, array first address), the index of the starting and ending elements in the array
================================================
*/
/*
====================================================
Algorithm idea Simple description:

Fast sorting is an essential improvement to bubble ordering. Its basic idea is to pass a trip
After scanning, the length of the sorted sequence can be greatly reduced. In bubble sort, once
Scans can only ensure that the maximum number of values is moved to the correct position, while the length of the sorted sequence may only
Reduced by 1. Quick sort by a scan, you can make sure that you have a number (base point)
The left is smaller than it is, and the number on the right is larger than it is. And then do it the same way.
It is the left and right sides of the number until the datum point is only one element to the left and right. It is by
C.a.r.hoare was introduced in 1962.

It is obvious that the quick sort can be implemented recursively, but the recursive implementation can also be solved by stack. Below the
Functions are implemented recursively, and interested friends can be converted to non recursive.

The quick sort is unstable. Optimal algorithm time complexity O (nlog2n), Worst O (n2)

=====================================================
*/
void Quick_sort (int *x, int low, int high)
{
int I, j, T;

if (Low < high)/* The element to be sorted starts and starts subscript, ensuring that the small is placed on the left and the large on the right. Here the following elements marked as low are reference points.
{
i = low;
j = high;
t = * (X+low); /* The number of temporary datum points * *

while (I<J)/* Cyclic scan * *
{
while (i<j && * (x+j) >t)/* On the right as long as the reference point is still large on the right/
{
j--; /* Move forward one position * *
}

if (I<J)
{
* (x+i) = * (X+J); /* The above loop exit: That is, the number of smaller than the Datum point, replace the number of reference points * *
i++; /* Move one position back, and use this as the reference point * *
}

while (i<j && * (x+i) <=t)/* On the left as long as the reference point is less than or equal to the left * * *
{
i++; /* Move one position back/*
}

if (I<J)
{
* (X+J) = * (X+i); /* The above loop exit: That is, the number of larger than the Datum point, put to the right/
j--; /* Move forward one position * *
}
}

* (x+i) = t; * * Once again after scanning, put to the appropriate position/
Quick_sort (x,low,i-1); /* Do a quick sort on the left side of the datum point * *
Quick_sort (X,i+1,high); /* Do a quick sort on the number to the right of the datum point.
}
}


/*
================================================
Features: Heap Sort
Input: Array name (that is, array first address), the number of elements in the array
================================================
*/
/*
====================================================
Algorithm idea Simple description:

Heap ordering is a sort of tree selection, which is an effective improvement of direct selection sort.
The heap is defined as follows: A sequence with n elements (h1,h2,..., HN), if and only if
Meet (Hi>=h2i,hi>=2i+1) or (hi<=h2i,hi<=2i+1) (i=1,2,..., N/2)
is called a heap. Only the heap that satisfies the former condition is discussed here.

As you can see from the definition of the heap, the top element of the heap (that is, the first element) must be the largest. A complete binary tree can
Represents the structure of a heap visually. The top of the heap is the root and the other is Zuozi and right subtree.
Initially, the sequence of numbers to be sorted is considered to be a two-forked tree in order, adjusting their order of storage,
Make it a heap, at which point the number of root nodes of the heap is the largest. Then the root node and the last node of the heap
Exchange. Then readjust the number of front (n-1) to make it a heap. And so on, until only two nodes
Heap, and exchange them, and finally get an ordered sequence of n nodes.

From the algorithm description, heap sorting requires two processes, one is to build a heap, and the other is to heap the top and the last element of the heap
Swap position. So the heap sort has two function components. One is to build the seepage function of the heap, and the other is to call the seepage function repeatedly
The function that implements the sort.

Heap sorting is not stable. Algorithm time complexity O (nlog2n).

*/
/*
Function: Infiltration builds the heap
Input: Array name (that is, array first address), number of elements involved in the build, starting with the first few elements
*/
void Sift (int *x, int n, int s)
{
int T, K, J;

t = * (x+s); /* Staging start Element * *
K = s; /* Start element subscript * *
j = 2*k + 1; /* Right subtree element subscript * *

while (J<n)
{
if (j<n-1 && * (X+J) < * (x+j+1))/* To determine whether the conditions of the heap are met: meet to continue the next round of comparison, otherwise adjust. */
{
j + +;
}

if (t<* (X+J))//* Adjustment/
{
* (X+K) = * (X+J);
K = J; /* adjustment, the start element will also be adjusted * *
j = 2*k + 1;
}
else/* No need to adjust, is already a heap, exit the loop. */
{
Break
}
}

* (x+k) = t; /* Start element put in its correct position * *
}


/*
Features: Heap Sort
Input: Array name (that is, array first address), the 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 Build heap * *
}

for (k=n-1; k>=1; k--)
{
t = * (x+0); * * Pile top put to the last * *
* (x+0) = * (X+K);
* (x+k) = t;
Sift (x,k,0); * * The remaining number to build a heap * *
}
}


void Main ()
{
#define MAX 4
int *p, I, A[max];

/* Input TEST data * *
p = A;
printf ("Input%d number for sorting:/n", MAX);
for (i=0; i<max; i++)
{
scanf ("%d", p++);
}
printf ("n");

/* Test selection Sort * *


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


/* Test Direct Insert Sort * *

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


/* Test Bubble sort * *

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

/* Test Quick Sort * *

/*
p = A;
Quick_sort (p,0,max-1);
*/

/* Test Heap sort * *

/*
p = A;
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.