Summary of sorting algorithms

Source: Internet
Author: User
Tags sorts

Various sort implementation codes:

#include <stdio.h>
#include <math.h>
#include <queue>
#include <vector>
#include <stack>
#include <map>
#include <string>
#include <cstring>
#include <algorithm>
#include <malloc.h>
#include <time.h>
#include <iostream>
using namespace Std;

int a[1010],b[1010];
void Selectsort (int a[],int p)//Simple Select sort
{
int n;
int m=p;
for (int i = 0; i < m; i++) {//Select I small record and swap in place
int j=i;
for (int k = i+1; k < m; k++) {//in A[I...M] Select the smallest record
if (A[k] < a[j])
J=k;
}
if (i! = j) {
N=A[J]; A[j]=a[i]; A[i]=n; Exchange with the first record
}
}
}

void Insertsort (int a[],int p)//Insert Sort
{
int m=p;
Int J;
for (int i = 2; i < P; i++) {
if (A[i] < a[i-1]) {//when "<" is required to insert a[i] into an ordered child table
A[0]=a[i]; Copy as Sentinel
for (j = i-1; A[0] < a[j];--j) {
A[J+1]=A[J]; Record and move back
}
A[J+1]=A[0]; Insert to correct position
}
}
}

void Bubblesort (int a[],int p)//bubble sort
{
int n;
int m=p;
while (M > 1) {//Indicates the last recorded Exchange
int lastindex=1;
for (int j=1; j < M; J + +) {
if (A[j-1] > A[j]) {
N=A[J]; A[J]=A[J+1]; A[j+1]=n; Exchange Records
Lastindex=j;
}
}
M=lastindex; The position of the last record in an unordered sequence in a trip
}
}

void Qsort (int *a, int left, int right)//Quick sort
{
if (left >= right)/* If the index on either side of the index is greater than or equal to the one that is already organized. */
{ br> return;
}
Int i = left,
int j = right;
int key = A[left];

while (i < j)/* control is searched for in the group */
{
while (I < J && Key <= A[j])
/* and the condition to find the end is, 1, find a number less than or greater than the key (greater than or less than depending on whether you want to increase the
Order or descending) 2, does not match the condition 1, and I and J size does not invert */
{
j--;/* looking forward */
}

A[i] = a[j];
/* After finding a number like this, assign it to the previous value of the removed I (if the first loop and key is
A[left], then it is to key) */

while (i < J && Key >= A[i])
/* This is I in the group to look forward, ibid, but note the size relationship with key stop cycle and the opposite,
because the idea of sorting is to throw the number to both sides, so the number of left and right side of the relationship between the size of the key and the opposite of */
{
i++;
}

A[j] = A[i];
}

A[i] = key;/* Returns the median key after it has been found in the group */
Qsort (A, left, i-1);/* Finally, the same way to the left side of the group to do the same thing */
Qsort (A, i + 1, */* In the same way to the right side of the group to do the same thing */
/* Of course there may be a lot of points in the end, until I = J of each group */
}

void merge (int sourcearr[],int temparr[],int start,int mid,int end)//merge sort
{
int i = Start,j=mid+1,k = start;
while (i! = mid+1 && J! = end+1)
{
if (Sourcearr[i] > Sourcearr[j])
temparr[k++] = sourcearr[i++];
Else
temparr[k++] = sourcearr[j++];
}
while (i! = mid+1)
temparr[k++] = sourcearr[i++];
while (j! = end+1)
temparr[k++] = sourcearr[j++];
for (i = start; I <= end; i++)
Sourcearr[i] = Temparr[i];
}

void mergesort (int sourcearr[],int temparr[],int start,int end)//internal use recursion
{
int mid;
if (Start > End)
{
Mid = (start + end)/2;
MergeSort (Sourcearr,temparr,start,mid);
MergeSort (Sourcearr,temparr,mid+1,end);
Merge (Sourcearr,temparr,start,mid,end);
}
}

void Hadjust (int array[],int i,int nlength)
{
int nchild;
int ntemp;
for (; 2*i+1<nlength;i=nchild)
{
Location of child nodes =2* (parent node location) +1
nchild=2*i+1;
Get the larger nodes in the sub-nodes.
if (Nchild<nlength-1&&array[nchild+1]>array[nchild]) ++nchild;
If the larger child node is larger than the parent node, move the larger child node up, replacing its parent node.
if (Array[i]<array[nchild])
{
Ntemp=array[i];
Array[i]=array[nchild];
Array[nchild]=ntemp;
}
else break; Otherwise exit the loop
}
}

void Hsort (int array[],int length)//heap sort algorithm
{
int i;
Adjusts the first half of the sequence of elements, after which it is the largest element of a sequence
Length/2-1 is the last non-leaf node, where "/" is divisible
for (I=length/2-1;i>=0;--i)
Hadjust (array,i,length);
Adjusts the sequence from the last element, shrinking the adjustment until the first element
for (I=length-1;i>0;--i)
{
Swap the first element with the last element of the current one,
The element that guarantees the current last position is the largest in this sequence now.
Array[i]=array[0]^array[i];
Array[0]=array[0]^array[i];
Array[i]=array[0]^array[i];
Continuously reduce the range of the adjustment heap to ensure that the first element is the maximum value of the current sequence at each adjustment
Hadjust (Array,0,i);
}
}

void Input (int a[],int p)
{
for (int i = 0; i < P; ++i)
{
cin>>a[i];
}
}

void Output (int a[],int p)
{
for (int i = 0; i < p-1; ++i)
{
cout<<a[i]<< "";
}
cout<<a[p-1]<<endl;
}
int main ()
{
int n;

cout<< "Number of input sorts:" <<endl;
cin>>n;

cout<< "Input sort number:" <<endl;
Input (A,n);

cout<< "Simple selection sort:" <<endl;
Selectsort (A,n);
Output (A,n);
cout<<endl;

cout<< "Insert sort:" <<endl;
Insertsort (A,n);
Output (A,n);
cout<<endl;

cout<< "bubble sort:" <<endl;
Bubblesort (A,n);
Output (A,n);
cout<<endl;

cout<< "Quick sort:" <<endl;
Qsort (A, 0, n-1);/* The third parameter in the original is reduced by 1 otherwise the memory is out of bounds */
Output (A,n);
cout<<endl;

cout<< "merge sort:" <<endl;
MergeSort (a,b,0,n-1);
Output (A,n);
cout<<endl;

cout<< "heap Sort:" <<endl;
Hsort (A,n);
Output (A,n);
cout<<endl;
return 0;
}

  1 #include <stdio.h> 2 #include <math.h> 3 #include <queue> 4 #include <vector> 5 #include & Lt;stack> 6 #include <map> 7 #include <string> 8 #include <cstring> 9 #include <algorithm> Ten #include <malloc.h> #include <time.h> #include <iostream> using namespace std; a[1010],b[1010 int]; 0 void Selectsort (int a[],int p)//Simple selection sort of (+/-int n; int m=p; + for (int i = +; I < m; i++) {//Select Select a small record of I and swap in place int j=i;  (int k = i+1; k < m; k++) {//in A[I...M] Select minimum Record (A[k] < a[j]), j=k;   + if (i! = j) {N=a[j]; a[j]=a[i]; a[i]=n;     Exchange with the first record of the records} (insertsort) (int a[],int p)//Insert sort x {m=p int; + int J; 36       for (int i = 2; i < P; i++) {PNS if (A[i] < a[i-1]) {//when "<"), the a[i] must be inserted into the ordered sub-table a[0]=a[i];  Copy as Sentinel 39           for (j = i-1; A[0] < a[j];--j) {a[j+1]=a[j];     ]=A[0];     Insert to the correct position bubblesort} (int a[],int p)//bubble sort (n); 51 int m=p; while (M > 1) {//indicates that the previous trip has recorded an interchange of Lastindex=1 int, and the (int j=1; j < M; J + +) { (A[j-1] > A[j])   {n=a[j]; a[j]=a[j+1]; a[j+1]=n; Interchange record of Lastindex=j;  M=lastindex}; The position of the last record in an unordered sequence in a single stroke. Qsort (int *a, int left, int right)//Quick sort (left >= right)/ * If the left index is greater than or equal to the index on the right, it means that a group has been collated. int j = right; int key = A[left];  while (I < j)/* control in the group look for once * * * * * * * (i < J && Key <= A[j]) 76/* and the search for the end condition is, 1, find a number less than or greater than key (greater than or less than depending on what you want to raise77 sequence or Descending) 2, does not meet the condition 1, and I and J size does not invert */~ ~ j--;/* Forward Search */80} 81 82 A[i] = A[j]; 83/* After finding a number like this, assign it to the value of the previous removed I (if the first loop and key is A[left], then it is to key) */-(I < J & amp;& key >= A[i]) 87/* This is I in the group to look forward, ditto, but note the size of the relationship between the stop cycle and the opposite, 88 because the order of thought is to throw the number to both sides, so the number of left and right side of the relationship between the size of the key is opposite * * The i++, a[j] = a[i]; 94} A[i] = key;/* When you have finished searching within a group, return the middle number key (A, left, i-1)./* Finally, use the same method as in the same way as in the group to which you split it. */9 8 Qsort (A, i + 1, right); */* Use the same approach to the group on the left-hand side (the same way) */99 * * Of course there may be a lot of points in the end, until I = J of each group */100}1 102 void Merge (int sourcearr[],int temparr[],int start,int mid,int end)//merge sort 103 {104 int i = START,J=MID+1,K = STA rt;105 while (i! = mid+1 && J! = end+1) 106 {107 if (Sourcearr[i] > Sourcearr[j]) 108 T emparr[k++] = sourcearr[i++];109 else110 temparr[k++] = sourcearr[j++];111}112 while (i! = mid+1) 113 temparr[k++] = sourcearr[i++];11 4 while (j! = end+1) temparr[k++] = sourcearr[j++];116 for (i = start; I <= end; i++) 117 Sourc Earr[i] = temparr[i];118}119 mergesort (int sourcearr[],int temparr[],int start,int end)//internal use recursive 121 {122 int mid;123 if (Start > End) 124 {$ mid = (start + end)/2;126 mergesort (sourcearr,temparr,start,mid ); 127 mergesort (Sourcearr,temparr,mid+1,end); Merge (sourcearr,temparr,start,mid,end); 129}130}131 hadjust void (int array[],int i,int nlength) 133 {134 int nchild;135 int ntemp;136 for (; 2*i+1<nlength;i=n Child) 137 {138//Sub-node position =2* (parent node position) +1139 nchild=2*i+1;140//Get the larger node in the child node 141 if (nchild< Nlength-1&&array[nchild+1]>array[nchild]) ++nchild;142//If the larger child node is larger than the parent node, move the larger child node upward, replacing its parent node 143 I F (Array[i]<array[nchiLD]) 144 {145 ntemp=array[i];146 array[i]=array[nchild];147 array[nchild]=ntemp ; 148}149 else break; Otherwise exit loop}151}152 153 void hsort (int array[],int length)//heap Sort algorithm 154 {155 int i;156//Adjusts the first half element of the sequence, after the second element is adjusted     is the largest element of the sequence 157//length/2-1 is the last non-leaf node, where "/" is divisible 158 for (i=length/2-1;i>=0;--i) 159 hadjust (array,i,length); 160         Adjusts the sequence starting from the last element, narrowing the adjustment until the first element 161 for (I=length-1;i>0;--i) 162 {163//swaps the first element and the last element of the current, 164         The element that guarantees the current last position is the largest of the 165 array[i]=array[0]^array[i];166 in the present sequence array[0]=array[0]^array[i];167 array[i]=array[0]^array[i];168//Reduce the range of the adjustment heap continuously, ensuring that the first element is the maximum value of the current sequence 169 hadjust (array,0,i); 170}1     }172 173 void Input (int a[],int p) 174 {175 for (int i = 0; i < P; ++i) 176 {177 cin>>a[i];178       }179}180 181 void Output (int a[],int p) 182 {183 for (int i = 0; i < p-1; ++i) 184 {185  cout<<a[i]<< ""; 186}187 cout<<a[p-1]<<endl;188}189 int main () {191 int n;192 19 3 cout<< "Number of input sorts:" <<endl;194 cin>>n;195 196 cout<< "Input sort number:" <<endl;197 input (a,n); 198 199 cout<< "Simple selection Sort:" <<endl;200 selectsort (a,n); 201 Output (A,n); 202 cout<<endl;2     204 cout<< "Insert sort:" <<endl;205 insertsort (a,n); 206 Output (A,n); 207 cout<<endl;208 209 cout<< "bubble sort:" <<endl;210 bubblesort (a,n); 211 Output (a,n); 212 cout<<endl;213 214 Cout&lt     ;< "Quick sort:" <<endl;215 Qsort (A, 0, n-1);/* The third parameter in the original is reduced by 1 otherwise the memory is out of bounds */216 Output (a,n); 217 cout<<endl;218 219 cout<< "Merge sort:" <<endl;220 mergesort (a,b,0,n-1); 221 Output (a,n); 222 cout<<endl; 223 224 cout<< "Heap sequencing:" <<endl;225 hsort (a,n); 226 Output (a,n); 227 cout<<endl; 228 return 0;229}

Conclusion:
Sorting methodsAverage Time Worst time       secondary storage
    simple sort  o (n2)        o (n2)         o (1)
     Quick Sort  o (NLOGN)     o (n2)          o (LOGN)
    heap sort   O (Nlogn)        o (NLOGN)      o (1)
     Merge sort  o (NLOGN)      o (NLOGN)       o (n)
    cardinality sort  o (d (n+rd))    o (d (N+RD))   o (RD)
Ps: Base order see next essay

Direct Insert sort, bubble sort to simple sort, hill sort, heap sort, quick sort for unstable sort

First, time performance

According to the average time performance, there are three kinds of sorting methods:
The methods of Time complexity O (NLOGN) are: fast sorting, heap sorting and merge sorting, in which quick sorting is the best;

The time complexity is O (n2): Direct insert sort, bubble sort, and simple select Sort, which are inserted directly as

The best, especially for those sequences of records that are similar in order to the keywords;

the sorting method with time complexity O (n) is only, the cardinality is sorted.

When the sequence of sequential records is ordered by keyword, the time complexity of O (n) can be achieved by direct insertion of sort and bubble sort, and for fast sorting, this is the worst case, when the time performance is degenerate to O (N2), so it should be avoided as much as possible. The time performance of simple selection sorting, heap sorting, and merge sorting does not change with the distribution of the keywords in the record sequence.

Second, the space performance

Refers to the amount of secondary space that is required during the sorting process.

1. All simple sorting methods (including: direct insertion, foaming, and simple selection ) and heap sorting have a spatial complexity of O (1);

2. Fast sorting to O (LOGN), as the necessary auxiliary space for the stack ;

3. Merge sort requires the most auxiliary space, its space complexity is O (n);

4. Chain cardinality sorting requires a queue end-to-end pointer, and the space complexity is O (RD).

Third, the stable performance of the sequencing method

1. A stable sorting method means that for records with two keywords equal, their relative positions in the sequence are not changed before and after sorting.

2. When ordering the LSD method for a sequence of records of multiple keywords , a stable sorting method must be used.

3. For an unstable sequencing method, simply cite an example to illustrate it.

4. Fast sorting and heap sorting are unstable sorting methods

Summary of 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.