Frequent use of sorting algorithms

Source: Internet
Author: User

Frequently used sorting algorithms

Here's a summary of code implementations that often use sorting algorithms

#include <iostream>
using namespace std;
typedef int elemtype;

/*
1. Insert Sort
(1) Direct insertion sorting algorithm
Algorithm thought: divides the equal rank sequence into the order and the disorderly two parts. Then insert the unordered part into the already ordered part, and finally

Can form an ordered sequence.
The operating procedures are as follows:
1) Find out the insertion position of the element L (i) in the table K;
2) The elements before the K element in the table are sequentially shifted back one position;
3) Copy L (i) to L (K).


*/
Time complexity: O (n^2)

void insertsort (elemtype arr[], int length) {int I, J; Elemtype Guard; Sentinel for (i = 1; i < length; ++i) {if (Arr[i] < arr[i-1])//Find an element in the unordered section.  After inserting it into the ordered part is still ordered {guard = arr[i];//copy to "Sentinel"//the element before element I is moved back one position for (j = I-1; ARR[J] > guard;              j--) {arr[j + 1] = Arr[j]; } arr[j + 1] = guard; Copy to insert location}}}  

/
2, binary insert sort
is used for linear tables that are stored sequentially in the sort table
when locating the insertion position. Use binary to find the
algorithm idea is:
1) Set the binary look up range;
2) binary find
3) move element
4) Insert Element
5) Continue operation 1), 2), 3), 4) step until the table is ordered.  
/

void binaryinsertsort (elemtype arr[], int length) {int I, j, low, High, mid; Elemtype tmp; for (i = 1; i < length; ++i) {tmp = Arr[i];//Copy to Sentinel//Set binary find range low = 0; High = i; while (low <= high)//binary Find {mid = (low + high)/2; if (Arr[mid] > TMP)//Find {high = Mid-1 in the left half; } else {low = mid + 1;//Find in right Half}}//Move element for (j = i-1; J >= High + 1;--j) {arr[j + 1] = Arr[j]; } arr[j + 1] = tmp; } }

/
3. Hill (Shell) sort
Basic idea:
First, the table to be sorted into a number of shapes if l[i, i+d, i+2d, ..., I+KD] of the "special" sub-table, respectively, the direct insertion sort.
Once the entire table has been "basically ordered," then a direct insert sort is made to the whole record.


Algorithm process:
1) Take a step d1 of less than N and divide all the records in the table into D1 groups. All records that are multiples of D1 are placed in the same group. In each
The direct insertion sort in the group.
2) Then take the second step D2 < D1, repeat step 1
3) until DK = 1, then the last direct insert sort
/

void shellsort (elemtype arr[], int length) {int I, j, dk = LENGTH/2; Elemtype tmp; while (DK >= 1)//control step {for (i = DK; i < length; ++i) {if (Arr[i] < arr[i- DK]) {tmp = Arr[i];//staging//Post-move for (j = i-dk; J >= 0 && tmp < ARR[J]; J-= DK) {arr[j + DK] = Arr[j]; } arr[j + DK] = tmp; }} DK/= 2; } }

/
4, bubble sort algorithm
Basic idea:
if the table to be sorted is N, the value of the adjacent element is compared to 22 from backward forward or from front to back. If it is in reverse order, then exchange it. Until the sequence is more complete.
Such a return is called a trip bubbling. The element with the larger value "sinks" and the smaller element is "floating".
Time complexity is O (n^2)  
/

void bubblesort (elemtype arr[], int length) {int I, J;      Elemtype tmp; for (i = 0; i < length-1; ++i)//Times {for (j = i + 1; j < length; ++j) {if (a                  Rr[i] > Arr[j]) {tmp = Arr[i];                  Arr[i] = Arr[j];              ARR[J] = tmp; }          }      }  }

/
5. High-speed sorting algorithm
Basic idea: Based on the division and treatment method. Any of the n elements to be sorted takes one element, pivot, as the datum. Divide the table to be sorted into a separate order by a trip
Two parts l[1..k-1] and l[k+1. N], so that all element values in the first part are smaller than pivot. and the entire element value in the second part is greater than pivot,
The datum element is placed at its last position, L (K), which is a high-speed sequence. And then recursively repeat the process for two sub-tables until each
There is only one element in the section or is empty, that is, all the elements are placed at their last position.

 /

int Partition (elemtype arr[], int left, int. right) {Elemtype pivot = Arr[left];//The first element in the current table is a pivot value while (left           < right) {//The position of the element that is smaller than the pivot value is found in the while (arr[right) >= pivot)          {--right; } Arr[left] = Arr[right];          Move an element that is smaller than the pivot value to the left//find the position of the element that is larger than the pivot value in the left-to-right and while (leave < OK && Arr[left] <= pivot)           {++left; } Arr[right] = arr[left];//Move the element larger than the pivot value to the right end} Arr[left] = pivot;  Place the pivot element at the last position return left; } void QuickSort (Elemtype arr[], int left, int. right) {if (left < right) {int pivotpos = Partiti On (arr, left, right); Divide QuickSort (arr, left, pivotPos-1); High-speed sort left half QuickSort (arr, Pivotpos + 1, right); High-speed sort right Half}}

/
6, simple selection sorting algorithm
Basic idea:
If the sort table is L[1...N], the I-trip sort selects keyword smallest element from the table to exchange with Li, The first order determines the
finally position of an element, so that the n-1 order can make the entire sort table orderly.  
/

void selectsort (elemtype arr[], int length) {int I, j, Min; Elemtype tmp; for (i = 0; i < length-1; ++i)//need n-1 trip {min = i; for (j = i + 1; j < length; ++j) {if (Arr[j] < arr[min])//each trip selects the lowest subscript of the element value { min = j; }} if (min! = i)//assuming that the value of the LI element of the trip to the trip finds the smallest element value, then the interchange so that the Li value is minimized {tmp = Arr[i]; Arr[i] = Arr[min]; Arr[min] = tmp; } } }

/
7, heap sorting algorithm
heap definition such as the following: N keyword serial number L[1..N] is called a heap only if the sequence satisfies:
1) L (i) <= L ( 2i) and L (i) <= L (2i+1) or 2) L (i) >= L (2i) and L (i) >= L (2i+1)
Meet the first case of the heap, called the small Gan (small top heap);
a heap that satisfies another situation. Called Dagen (large Top heap).  
/

void Heapadjust (elemtype *a,int i,int size)//adjustment heap {int lchild = 2 * i;     I's left child node ordinal int rchild = 2 * i + 1;            I's right child node ordinal int max = i; Temporary variable if (i <= SIZE/2)//Assuming I is a leaf node it is not necessary to adjust {if (lchild <= size && A[lchild] &G T A[max] {max = Lchild;//left child is larger than parent value, need to adjust} if (rchild <= size && a[r Children] > A[max]) {max = rchild;//the right child is larger than the parent value.              Need to adjust} if (max! = i)//need to adjust {elemtype tmp = A[max];              A[max] = A[i];              A[i] = tmp;    Heapadjust (A, max, size); Avoid resizing a subtree with Max as the parent node is not a heap}}} void Buildheap (elemtype *a,int size)//Build heap {for (int i = SIZE/2; I >= 0;          i--)//non-leaf node maximum ordinal value is SIZE/2 {heapadjust (A, I, size);      }} void Heapsort (Elemtype *a, int size)//heap Sort {buildheap (a,size); for (int i= Size-1; I >= 0;           i--) {swap (a[0], a[i]);        Swaps the top of the heap and the last element, that is, each time the largest of the remaining elements is placed to the last face Buildheap (A, i-1);      Once again, the remaining elements are established as large top heap heapadjust (a,1,i-1);           Resize the heap top node again to become a big Top heap}} void Display (Elemtype arr[], int length) {for (int i = 0; i < length; ++i) {      cout << Arr[i] << "";  } cout << Endl;      } int main () {elemtype arr[] = {2, 1, 5, 3, 4, 0, 6, 9,-1, 4, 12};      Insertsort (arr, sizeof (arr)/sizeof (elemtype));      Binaryinsertsort (arr, sizeof (arr)/sizeof (elemtype));      Shellsort (arr, sizeof (arr)/sizeof (elemtype));      Bubblesort (arr, sizeof (arr)/sizeof (elemtype));      QuickSort (arr, 0, sizeof (arr)/sizeof (Elemtype)-1);      Heapsort (arr, sizeof (arr)/sizeof (elemtype));      Display (arr, sizeof (arr)/sizeof (elemtype));  return 0; }

Use sorting algorithms frequently

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.