1, sorting algorithm

Source: Internet
Author: User
Tags for in range

In both C + + and Java, the corresponding library provides a sort function. For example, <algorithm> in C + + provides the sort function. However, to understand the principles of common sorting algorithms, in the interview or work have some help. Below, the common sorting algorithm is combed.

Common sorting algorithms are: insert sort, choose sort, bubble sort, hill sort, quick sort, merge sort, base sort, heap sort .

First, insert sort

  1, thought : Referring to the insertion sort, a friend gave me a very expressive chestnut, simple image, easy to understand. We all play poker, in general, after we grab the cards are placed in the hands of the order. Whenever we catch a new card, we insert the card into the orderly hand. This is in line with the idea of inserting a sort, inserting new elements into an ordered sequence.

  7 6 1 5 3, at the beginning, we had a hand 7, it was ordered (an element), and then we picked up a 6, smaller than 7, both exchanged.

6 7 1 5 3, then came a 1, and took it and ordered sequence 6,7 comparison, inserted into the starting position

1 6 7 5 3, then came a 5, and took it and ordered sequence 1,6,7 comparison, insert

1 5 6 7 3, finally came a 3, take it and ordered sequence 1,5,6,7 comparison, insert

1 3 5 6 7, get sorted results

Show me the code. Let's take a look at the implementation codes for C + +.

 for (int i=1; i<v.size (); i++) {    int key = v[i];     int j = i1;      while 0 && v[j] > key) {            v[j+1] = v[j];            J--;    }    V[j+1] = key;}

Then we'll look at the python implementation.

  Insert_sort (lists): Count  = Len (lists)   i in  range (1,count) key  = Lists[i] J  = i-1 while  J >= 0:  if  lists[i] > key: Lists[j  + 1] = Lists[j] Lists[j]  = key J -= 1 return  lists  

It is important to note that the C + + implementation and Python implementations differ in the details of exchanging data. C + +, if the value in the sort sequence is smaller and j>=0 than key, I move the sort sequence to the right in turn, until it is not satisfied, and we assign the key to that position. In Python, when the condition is met, the two adjacent elements are exchanged.

The implementation details are different, but the two ideas are consistent.

  2, the complexity of time

The outer loop is the number of sequences to be sorted n, within the loop, if you consider completely your virtual situation, you need to exchange data (mobile data) n times, so the time complexity of O (n^2).

Second, choose the sort

The idea of choosing sort is simple and rude. Find the smallest value from the sequence, put it in the first position, and then find the smallest value in the remaining elements placed in the second position ... bulabula ... There is a very popular argument that the Xuanza realize sort is a fixed position to find the element, while the insertion sort is a fixed element to find the position. Very image.

 for(intI=0; I<v.size (); i++){    intMin =V[i]; inttemp; intindex =i;  for(intj = i +1; J < V.size (); J + +){        if(V[j] <min) {min=V[j]; Index=J; }} Temp=V[i]; V[i]=min; V[index]=temp;}

Again, let's look at Python implementations.

def select_sort (lists):     = Len (lists)      for in range (0, count):        = i        for  in range (i + 1, count):            if lists[min] < lists[j]:                =J         = lists[i], lists[min]    return lists

Third, bubble sort

  1, thought . Bubble sort, as the name of the person, if you consider ascending, is to compare the size of the adjacent elements, the small element left, the large element to the right, after a round of movement, you can move the smallest element to the leftmost, or the largest element to the far right. It floats like a bubble (the small element moves left), or the stone falls to the bottom (the large element shifts to the right). Two kinds of mobile methods, you can choose by their own preference.

Time complexity O (n^2).

C + + code, move the small element left.

 for(intI=0; I<v.size (); i++){    inttemp =0;  for(intJ=v.size ()-1; J >I; j--){        if(V[j] < v[j-1]) {temp=V[j]; V[J]= v[j-1]; V[j-1] =Temp }    }
}

Python code, large element right shift.

def bubble_sort (lists):     = Len (lists)      for in range (0, count):        for in Range (j+1, count):            if lists[i] > lists[j]:                = lists[j], lists[i]     return lists

 2, the optimization of bubble sort

If the exchange of bubbles is not found in a round order, then the unordered sequence to be sorted is in fact "orderly". Therefore, the bubble sort can be terminated after this round is sorted. To do this, we add a flag bit flag, which is set to false before each round of sequencing, and is set to true if an interchange occurs during the sorting process. Check flag at the end of each round and terminate the algorithm if no swap has occurred.

BOOLFlag; for(inti =0; I < len-1; i++) {     inttemp =0; Flag=false;  for(intj = len-1; J >I; j--) {         if(Ar[j] < ar[j-1]) {temp=Ar[j]; AR[J]= Ar[j-1]; Ar[j-1] =temp; Flag=true; }     }     if(!flag) {          Break; } }

Another way of writing

voidNewbubblesort (intA[],intN) {    int Exchange; inttemp; intj=0;  Exchange  = N1;  while(  Exchange ) {  exchange  =0;  for(j =0; J < N-1; j + + ){            if(A[j] > a[j+1]) {temp=A[j]; A[J]= a[j+1]; A[j+1] =temp; Exchange =J; }        }    }}

Take the time to write this, the neck is very sour ah ....

  

1, sorting algorithm

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.