Summary of sorting algorithms

Source: Internet
Author: User
Tags sorts

I will make a summary of several classic sorting algorithms, focusing on the implementation of the Code.

Sorting algorithms are bubble sort, quick sort, direct insert sort, hill sort, select sort, etc.

Sort algorithm 1: bubble sort

Algorithm principle: (from back to forward)
    1. Compares the adjacent elements. If the first one is bigger than the second one, swap them both.
    2. Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. At this point, the last element should be the maximum number.
    3. Repeat the above steps for all elements, except for the last one.
    4. Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.

Algorithm Analysis:

Complexity of TimeIf the initial state of the file is positive, a single scan will complete the sequencing. The required number of keyword comparisons C and the number of records moved M have reached the minimum: C (min) =n-1,m (min) =0 so, the best time complexity for bubbling sorting is O (n). If the initial file is reversed, a n-1 sequence is required. Each order is compared to the N-i keyword (1≤i≤n-1), and each comparison must move the record three times to reach the Exchange record location. In this case, the comparison and the number of moves reached the maximum: The worst time complexity for the C (max) =o (n2) M (max) =o (n2) Bubble sort is O (N2). Overall, the average time complexity for the bubble sort is O (N2). algorithm Stability: An unstable sorting algorithmThe bubble sort is to move the small element forward or the large element back. The comparison is an adjacent two element comparison, and the interchange also occurs between these two elements. So, if the two elements are equal, I think you will not be bored to exchange them again, if the two equal elements are not adjacent, then even through the preceding 22 exchange two adjacent together, this time will not be exchanged, so the same elements of the order has not changed, so bubble sort is a stable sorting algorithm. Core code:
1  for(intI=0; i<n-1; i++)2    for(intj=0; j<n-1-i;j++)3     if(a[j]>a[j+1] )4    {5       inttemp=A[j];6a[j]=a[a+1];7a[j+1]=temp;8    }9 Ten //or One  A int BOOL=0;//used to determine if an array has been ordered -  for(inti=n-1; i<=1,BOOL==0; i++) - { the   BOOL=1;//set the order first -    for(intj=0; j<i-1; j + +) -     if(a[j]>a[j+1] ) -     {  +        //... Exchange A[j] and a[j+1] -        BOOL=0;//Tag Array unordered +     } A}

Sort algorithm 2: Quick sort (improvements to bubble sort)

Basic idea: By a trip to sort the data to be sorted into two separate parts, one part of all the data is smaller than the other part of all the data, and then according to the method of the two parts of the data are quickly sorted, the entire sorting process can be recursive, so as to achieve the entire data into an ordered sequence.

A quick sorting algorithm is: 1) Set two variables I, J, when the sort begins: I=0,j=n-1;2) takes the first array element as the key data, assigns the value to Key, i.e. Key=A[0];3) forward search from J, that is, after the start of a forward search (j--), find the first less than KeyValue a[j], a[j] and A[i] interchange, 4) from I start backward search, that is, to start backward search (i++), to find the first one greater than KeyA[i], will a[i] and A[j] interchange; 5) Repeat 3rd, 4, until i=j; (3,4 step, no value matching the criteria, that is, 3 a[j] is not less than Key, 4 A[i] not greater than KeyChange the value of J, I so that j=j-1,i=i+1 until it is found. Locate the value that matches the condition, and the J pointer position does not change when I exchange it. In addition, I==J this process must be exactly when the i+ or J completes, at which time the loop ends). algorithm Stability: An unstable sorting algorithmfast sorting is not a stable sorting algorithm, which means that the relative position of multiple identical values may change at the end of the algorithm. Core code:
1 //perform a quick sort2 intQuickintS[],intStartintend)3 {4   inti,j;5I=start;6j=end;7s[0]=s[start];//Set Datum values8   while(i<j)9  { Ten       while(I<j && s[j]>s[0] ) Onej--;//position shift left A      if(I&LT;J)//when S[j]<=s[0] -      { -S[I]=S[J];//Place S[j [] less than or equal to the base value] in s[i] position thei++; -      }   -  -      while(I<j && s[i]<=s[0] ) +i++;Position right Shift
- if(i<j) // when S[j]>s[0]
+ { As[j]=S[i]; //s[i] to s[j] position with greater than base value
atj--; - } - } -s[i]=s[0]; //Put datum values in the specified position
- if(start<i) -Quick (s,start,j-1); //recursion of segmented parts
in if(end>i) -Quick (s,j+1, end); to}

Sort algorithm 3: Direct Insert Sort

Algorithm idea: Every time the first element is removed from the unordered table, it is inserted into the proper position of the ordered table, so that the ordered table is still orderly.

The first two numbers are compared, then the second number is inserted into the ordered table by size, and the second one scans the third data with the first two numbers, inserts the third number into the ordered table by size, and then goes through the n-1 scan to complete the sorting process. algorithm Stability: Stability ranking algorithmCore code:
1  for(intI=2; i<=n;i++)2 {3s[0]=s[i];//S[0] As a surveillance whistle4j=i-1;//traversing an ordered array from right to left5    while(s[0]&LT;S[J])//find S[0] where to insert6   {7s[j+1]=S[J];//The lookout is small, the data shifts right.8j--;9    }Tens[j+1]=s[0];//Insert the lookout post at a certain location S[0] One}

Sort algorithm 4: Hill sort (improvement of direct insertion sort)

Basic idea: First take an integer less than n D1 as the first increment, and group all the records in the file. All records with a multiple of D1 are placed in the same group. First, the direct insertion sort is performed within each group, and then the second increment d2<d1 repeats the above groupings and sorts until the increment equals 1, that is, all records are placed in the same group for direct insert sorting.

Algorithm Stability: An unstable sorting algorithm

Because of the number of insertions, we know that one insert sort is stable and does not change the relative order of the same elements, but in different insertion sorts, the same elements may move in their own insert sort, and finally their stability will be disturbed, so the shell sort is unstable.

Core code:

1  while(k>0)//K for increments2 {3    for(i=k;i<n;i++)4   {5j=i-K;6       if(a[j]>a[j+K])7       {8           inttemp=A[j];9a[j]=a[j+1];Tena[j+1]=temp; One       } A   } -K/=2;//Increment k Decrease -}

Sort algorithm 5: Select sort

Algorithm idea: Each trip selects the smallest (or largest) element from the data element to be sorted, placing the order at the end of the ordered sequence until all the data elements to be sorted are finished.

Algorithm Stability: An unstable sorting algorithm

The choice of sorting is to choose the smallest current element for each location, such as selecting the smallest one for the first position, selecting the second small for the second element in the remaining element, and so on, until the n-1 element, the nth element is not selected, because it is left with one of its largest elements. So, in a trip, if an element is smaller than the current element, and the small element appears behind an element that is equal to the current element, then the post-swap stability is destroyed. Rather awkward, for example, sequence 5 8 5 2 9, we know that the first time to select the 1th element 5 and 2 Exchange, then the original sequence of 2 and 5 of the relative sequence is destroyed, so the selection is not an unstable sorting algorithm.

Core code:

1  for(intI=0; i<n-1; i++)2    for(intj=i+1; j<n;j++)//find the smallest (largest) number in the remaining array3      if(A[i]>a[j])//in the back of an ordered array4      {5           inttemp=A[i];6a[i]=A[j];7a[j]=temp;8}

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.