Sort and re-learn-bubble, fast, merge, heap sort

Source: Internet
Author: User

1. Bubble sort

Each time you compare the two numbers in the array, if the order you expect is inconsistent, swap the two numbers, and one loop can put a number in the correct position. The outer loop requires N-1 times, because the number of N-1 has been placed in the correct position, and the nth number is already correct. The inner loop can also be N-1 times, or each time less than the last one, the first case will compare already ordered parts, the second situation has been sorted parts need not be compared. or two-layer loops are N-1 times better to write.

voidBubble_sort (intArray[],intN) {    intI, J, temp;  for(i =0; I < n-1; i++ )    {         for(j =0; J < N-1; J + + )        {            if(Array[j] > array[j+1]) {temp=Array[j]; ARRAY[J]= array[j+1]; Array[j+1] =temp; }        }    }    return;}

The inner loop is reduced one at a time

voidBubble_sort (intArray[],intN) {    intI, J, temp;  for(i =0; I < n-1; i++ )    {         for(j =0; J < N-1I J + + )        {            if(Array[j] > array[j+1]) {temp=Array[j]; ARRAY[J]= array[j+1]; Array[j+1] =temp; }        }    }    return;}
2. Quick Sort

In the online search a few articles to introduce the quick sort, personal feeling this article "sit on the toilet look algorithm: Quick sort" very good, there is a good understanding of the figure. Most of the following are excerpted from this article.

Website: http://developer.51cto.com/art/201403/430986.htm

The idea of quick sorting is relatively simple, and the whole sequencing process is divided into three steps:

    1. Select an element in the array as the Datum value (pivot)
    2. All elements that are less than the datum are moved to the left of the datum, and the elements greater than the datum are moved to the right of the Datum
    3. For the two subsets on the left and right sides of the datum, repeat the first and second steps until only one element is left in all the subsets

Array to sort: 6 1 2 7 9 3 4 5 10 8

1. Select the leftmost 6 for the first time as the base value

2. Starting from the right, select the first number less than 6, the subscript decrements, i.e. j--

3. From the left to select the first number greater than 6, subscript increment, that is, i++

4. Swap these two values, i.e. Exchange 7 and 5

5. At this time I! = j, continue looking for

6. Second Exchange 9 and 4

7. Once again, I will be equal to J, then the Exchange benchmark value and Array[i]

8. At this point 6 the left number is all less than 6, 6 to the right of the number is all greater than 6, the next to the two sub-sequence to do the same operation.

There are several conditions to note when writing code, and when starting a scan, I must always be less than j,i and J equal when exchanging with the reference value. In addition, when recursive invocation, determine whether low is less than high, otherwise you need to compare low and hign in the Quick_sort function.

voidQuick_sort (intArray[],intLowintHigh ) {    int Base=Array[low]; inti =Low ; intj =High ; inttemp;  while(I! =j) {/*find the first number less than the base value from the right*/         while(Array[j] >=Base&& i < J) j--; /*find the first number greater than the base value from the left*/         while(Array[i] <=Base&& i < J) i++; if(I! =j) {Temp=Array[j]; ARRAY[J]=Array[i]; Array[i]=temp; }    }    /*at this point the i==j, and the reference value Exchange*/Array[low]=Array[i]; Array[i]=Base; /*Continue to do the same for two sub-sequences*/    if(Low < I-1) Quick_sort (array, low, I-1); if(i +1<High ) Quick_sort (array, I+1, high); return;}
3. Merge sort

The core idea of merge sorting is to combine two sorted sub-sequences into a sequence with a time complexity of O (N). How do you get ordered sub-sequences? The entire sequence is divided by two until each element is a subsequence. Then merge each sub-sequence in turn. The decomposition process is implemented recursively, and the time complexity is O (Logn), so the time complexity of merge sort is O (Nlogn).

voidMerge_array (intArray[],intLowintMidintHigh ) {    inti = low, J = mid +1; intm = Mid, n =High ; intK =0; int*temp =New int[high-low+1]; /*merge two ordered sequences Array[low...mid] and Array[mid+1...high]*/     while(I <= m && J <=N) {if(Array[i] <=Array[j]) {Temp[k+ +] = array[i++]; }        Else{temp[k+ +] = array[j++]; }    }    /*one sequence will be left, then all elements of this sequence will be copied to the temporary array*/     while(I <=m) {temp[k+ +] = array[i++]; }     while(J <=N) {temp[k+ +] = array[j++]; }    /*copy back to the original array*/     for(i =0; I < K; i++) {Array[low+i] =Temp[i];    } Delete [] temp; return;}voidMerge_sort (intArray[],intLowintHigh ) {    if(Low <High ) {        intMid = (low + high)/2; //printf ("%d%d%d\r\n", Low, Mid, high);Merge_sort (Array, low, mid); Merge_sort (Array, Mid+1, high);    Merge_array (Array, Low, mid, high); }    return;}
4. Heap sequencing

This section contains information from http://www.cnblogs.com/zabery/archive/2011/07/26/2117103.html

Heap is divided into Dagen and small Gan, is a complete binary tree, Dagen the requirement is that each node value is not the value of its parent node, in the array of non-descending order, need to use the large root heap, because according to the requirements of Dagen, the maximum value must be at the top of the heap. You first need to convert the array into piles and adjust the heap to meet Dagen requirements. See, the array is a = {1, 3, 4, 5, 7, 2, 6, 8, 0}

Operation Steps

1. Array a conversion piles in the form of Figure 1.1, the parent node of the left leaf node is 2*i+1, the right leaf node is 2*i+2,i starting from 0

2. The process of heap transfer starts from the last non-leaf node , as shown in Figure 1.1, the last non-leaf node is a[3]=5

If the array has an odd number, then the last non-leaf node has two children, that is, the last non-leaf node of the right child is the last value of the array, then the following expression is established 2*i+2 = n-1, the i= (n-3)/2
If the array has an even number, then the last non-leaf node has the left child, the left child is the last value of the array, 2*i+1 = N-1, i= (n-2)/2
Since division sign only retains the integer part, the two expressions calculate that I is equal, and in the following code we put (n-2)/2 as the last non-leaf node

3. Figure 1.4 In contrast to figure 1.3, 3 and 8 exchange, at this time 3 is less than its left child 5, so 3 and 5 also want to exchange, drawing figure 1.5. Figure 1.6 to figure 1.7 also has two exchanges, so adjust the heap to be aware of the definition of Dagen, that is, the value of each node is not more than the value of its parent node. The loop is judged until it meets the requirements.

4. After each adjustment of the heap, the first element of the heap is the maximum value of the current heap, and then the element is swapped with the last element of the heap, the number of heap elements is reduced by one, the heap continues to be adjusted, the last element of the heap is swapped, and so on, until the number of elements in the heap remains 1

/*N: Number of elements I: root node of subtree to be compared*/voidAdjust_heap (intArray[],intNinti) {    intleft =2* i +1; intright =2* i +2; intlargest =i; inttemp;  while(Left < n | | Right <N) {/*find the largest value in the root node and two leaf nodes*/        if(Left < n && Array[largest] <Array[left]) {Largest=Left ; }        if(Right < n && Array[largest] <Array[right]) {Largest=Right ; }        /*If the root node is not the maximum value, swap with the maximum value*/        if(Largest! =i) {temp=Array[largest]; Array[largest]=Array[i]; Array[i]=temp; /*The implementation of step 3, the loop to compare the entire subtree to meet the requirements*/I=largest; Left=2* i +1; Right=2* i +2; }        Else        {             Break; }    }    return;}voidBuild_heap (intArray[],intN) {    inti; /*the implementation of step 2, starting from the last non-leaf node to adjust the heap until the root node*/     for(i = (n-2)/2; I >=0; i--) {adjust_heap (array, n, i); }    return;}voidHeap_sort (intArray[],intN) {    intI, temp;    Build_heap (array, n); /*the implementation of step 4, each cycle of the first element of the exchange heap and the last element, the heap size minus 1 each time, because each time the heap is adjusted, the first element of the heap is the maximum value of the current heap, after exchange to get a well-ordered array*/     for(i = n-1; i >0; i--) {Temp= array[0]; array[0] =Array[i]; Array[i]=temp; Adjust_heap (Array, I,0); }    return;}

Sort and re-learn-bubble, fast, merge, heap sort

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.