A sort algorithm for exchanging classes in layman's

Source: Internet
Author: User

 1) Bubble sort

Bubble sort is a relatively simple one in many sorting algorithms, the basic idea is to repeat the sequence of the entire series, a comparison of two elements ( 22 sort ), if they do not conform to the exchange, repeat this until the sequence no longer need to exchange the number (end condition). just like bubbles, light bubbles will float upward, and in the process of continuous floating, there is a 22 exchange process, so called bubble sort.

In fact, you can also use examples of life to understand, such as: in the military training line, according to the height and short order of the arrangement, tall and short will be 22 to compare.

Let's look at the process of the algorithm in general:

Select a set of sequences 4, 3, 5, 6, 2, 1 (extreme)

Bubble sort from the beginning, 1th and 2nd are exchanged, 4 > 3, so need to exchange:

-- 3, 4, 5, 6, 2, 1

No. 2nd and 3rd are exchanged,4<5, not exchanged.

-- 3, 4, 5, 6, 2, 1

No. 3rd and 4th are exchanged,5<6, not exchanged.

-- 3, 4, 5, 6, 2, 1

Number 4th and 5th,6>2, Exchange

-- 3, 4, 5, 2, 6, 1

Number 5th and 6th,6>1, Exchange

-- 3, 4, 5, 2, 1, 6

The first bubble sort ends, the largest number is swapped to the last one, so loop until there is no element to swap, and the bubble sort ends.

The code is implemented as follows:

?
1234567891011121314 void BubbletSort(int*a,int len) {    int m;    for (bool bSwap=true; bSwap; len--) {        bSwap = false;        for (int j=1;j<len;j++) {            if (a[j-1]>a[j]) {   // 交换值                m=a[j];                a[j]=a[j-1];                a[j-1]=m;                bSwap=true;            }        }    }}

In fact, bubble sort overall seems to be very "silly", there is a lot of room to optimize. For example, if you find that the smaller element is in the back, swap two adjacent elements, and if I only scan the elements, write down the smallest element, wait a scan, then swap the two, so that the smallest element is in front, each scan, only need a real exchange, and just the bubbling may need to be exchanged several times, Just said the algorithm optimization is in fact the choice of sorting, I will elaborate later, he belongs to the category of choice sorting.

Let's consider the complexity of the bubbling algorithm:

  in time complexity, if the sequence to be sorted is in full reverse order, then the exchange between the elements is required each time, so the time complexity is O (), if ordered, that is, do not need to exchange elements, but need to scan, so still need O () time complexity, On average, the time complexity is O ().

in space complexity, there is only one m required for the auxiliary space (as in the above code), so the spatial complexity is O (1).

2) Quick Sort

If you remember the binary insert sort process: in an ordered sequence, insert the keyword and the binary sequence of the middle keyword to compare, if the small is on the left side of the keyword, if the larger is the keyword to the right. The difference between a quick sort and a binary insert sort is that the sequence in which the binary insert sort inserts itself is an ordered sequence, and the two sides are ordered when the middle keyword is selected. And the quick sort is that it is not necessarily orderly, its operation is: randomly select a keyword (the general selection of the first), so that all the keywords and it is compared once, the small on the left side, large on its right, and then recursively to the left and the right to sort. By comparing all the numbers in the interval with the keywords, we can complete the split operation in a linear time.

Let's look at the steps of the algorithm:

Initial state: "49,38,65,97,76,13,27,49 '"
  once divided: "27,38,13" 49 "76,97,65,49"
  to quickly sort by: "13" 27 "38" "49", 65 "76" 97 "
  ordered sequence: "13,27,38,49,49 ', 65,76,97"

The above is the approximate steps of the algorithm, the general completion of the segmentation operation has a lot of tricks of the implementation method, such as the most commonly used is to define two pointers, one from the search to find a larger than the keyword, one from the back to find a smaller than the keyword, and then the two pointers corresponding to the element exchange position and continue to move the pointer This is only a general approach, and there are a lot of details about the implementation.

Let's take a look at the detailed steps for a quick round of sorting:

The original sequence (I and J, respectively, points to the lowest and highest positions of the sequence):


Select the first number 49 as the comparison sort key.

1, using J, starting from the right end of the sequence of the scan encountered less than 49 is stopped.


2. Swap 27 to the position of I


3, using I, starting from the left end of the sequence of the scan encountered more than 49 of the number is stopped


4, swap 65 to the position of J


5, then use J Forward scan encountered than 49 small 13 stop, and the 13 switch to I position.


6, use I backward scan encountered than 49 large 97 stop, and swap to the position of J

7, continue to use J forward scan encountered than 49 small and stop, then found I and J meet, representing the end of the scan.


8. Put 49 in the IJ position at the end


As can be seen from the above round of quick row, 49 divides the entire sequence into two parts, less than 49 on its left, greater than 49 on its right. According to the idea of the algorithm, the 492-side sequence is ordered again. In addition, from the whole ordering process, the whole sequence is first a quick row, and then the sub-sequence of the second order, so repeatedly until the order, the whole process is a recursive thought. So the code is better written, let's implement it.

?
12345678910111213141516171819202122232425262728293031323334 // head=>序列的开头// tail=>序列的结尾void quickSort(int array[], int head, int tail) {    if (head > tail) {        return;    }    // i,j指向头和尾巴    int i=head;    int j=tail;    int iPivot=array[i]; /**< 选取枢轴 */    while (i<j) {        // 使用j,从序列最右端开始扫描,直到遇到比枢轴小的数        while ((i<j) && (iPivot <= array[j])) {            j--;        }        // 交换位置        if (i<j) {            array[i++]=array[j];        }        // 使用i,从序列最左端开始扫描,直到遇到比枢轴小的数枢轴大的数        while ( (i<j) && (array[i] <= iPivot) ) {            i++;        }        // 交换位置        if (i<j) {            array[j--]=array[i];        }    }    // 最后填入枢轴位置    array[j]=iPivot;    // 这里就是对枢轴两边序列进行排序的递归调用    quickSort(array, head, i-1);    quickSort(array, i+1, tail);}

The code has been rigorously tested and generally does not have a problem. Let's take a look at the complexity of time and complexity of space.

Quick sorting has a feature, the more the order of the sequence is close to the disorder, the higher the efficiency of the algorithm, that is, in the basic order of time Complexity is O (), the best case is O (), the average complexity of O (), from all within the order, the fast row is all within the ranking of the average complexity of the best In addition, the spatial complexity is O (). Because the above algorithm implementation is recursive, recursive needs stack space.

http://kb.cnblogs.com/page/185060/

A sort algorithm for exchanging classes in layman's order (RPM)

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.