Eight kinds of sorting algorithms that must be known "Java Implementation" (c) Merge sort algorithm, heap sorting algorithm detailed

Source: Internet
Author: User

First, merge sort algorithm

Basic idea:

Merge (merge) sorting method is to combine two (or more than two) ordered tables into a new ordered table, that is, the ordered sequence is divided into several sub-sequences, each sub-sequence is ordered. Then the ordered subsequence is combined into a whole ordered sequence.

Merge Sort Example:

Merge method:

Set R[I...N] consists of two ordered sub-tables R[I...M] and R[M+1...N], two sub-table lengths are N-i + 1, n-m.

      1. J=m+1;k=i;i=i; Starting subscript for two sub-tables and starting subscript for auxiliary arrays
      2. If I>m or j>n, turn ⑷//one of the sub-tables has been merged, the comparison selection is finished
      3. Select R[i] and r[j] smaller deposit auxiliary array RF
        If r[i]<r[j],rf[k]=r[i]; i++; k++; turn ⑵
        otherwise, rf[k]=r[j]; j + +; k++; turn ⑵
      4. Depositing elements of a child table that has not yet been processed into the RF
        If i<=m, place r[i...m] in RF[K...N]//previous sub-table non-empty
        If j<=n, place R[J...N] in RF[K...N]//After a sub-table is not empty
      5. End of merge.

Algorithm implementation:

/*** Merge Sort * Introduction: Merging two (or more than two) ordered tables into a new ordered table divides the ordered sequence into a number of sub-sequences, each of which is ordered. Then the ordered Subsequence is merged into the whole ordered sequence * time complexity is O (nlogn) * Stable sorting method *@paramnums Array to sort *@returnoutput an ordered array*/     Public Static int[] Sort (int[] Nums,intLowintHigh ) {        intMid = (low + high)/2; if(Low <High ) {            //leftsort (nums, low, mid); //RightSort (Nums, Mid + 1, high); //merge right and leftmerge (Nums, Low, Mid, high); }        returnNums; }    /*** Sort the number of low to high positions in the array *@paramnums Array to sort *@paramLow start position for row *@parammid-row Middle position *@paramHigh pending End position*/     Public Static voidMergeint[] Nums,intLowintMidintHigh ) {        int[] temp =New int[High-Low + 1]; inti = low;//left Pointer        intj = mid + 1;//Right Pointer        intK = 0; //move the smaller number first to the new array         while(I <= mid && J <=High ) {            if(Nums[i] <Nums[j]) {Temp[k+ +] = nums[i++]; } Else{temp[k+ +] = nums[j++]; }        }        //Move the left remaining number into the array         while(I <=mid) {temp[k+ +] = nums[i++]; }        //move the remaining number in the right side into the array         while(J <=High ) {Temp[k+ +] = nums[j++]; }        //overwrites the number in the new array with the Nums array         for(intK2 = 0; K2 < Temp.length; k2++) {Nums[k2+ Low] =TEMP[K2]; }    }

Second, heap sorting algorithm

1. Basic ideas:

Heap sorting is a sort of tree selection, which is an effective improvement on direct selection sorting.

Heap definition: A sequence with n elements (h1,h2,..., HN), when and only if satisfied (hi>=h2i,hi>=2i+1) or (hi<=h2i,hi<=2i+1) (i=1,2,..., N/2) is called a heap. Only the heap that satisfies the former condition is discussed here. As can be seen from the definition of a heap, the top element of the heap (that is, the first element) must be the largest (large top heap). A fully binary tree can represent the structure of a heap visually. Heap top is the root, the other is Zuozi, right subtree.

Thought: Initially, the sequence of numbers to be sorted is considered to be a two-fork tree of sequential storage, adjusting their storage order to make it a heap, when the heap has the largest number of root nodes. The root node is then exchanged with the last node of the heap. The number of fronts (n-1) is then re-adjusted to make it a heap. And so on, until there are only two nodes of the heap, and exchange them, and finally get an ordered sequence of n nodes. In terms of algorithm description, heap sequencing requires two processes, one is to build the heap, and the other is the last element of the heap to exchange the position. So the heap sort has two functions. One is to build the seepage function of the heap, and the second is to call the function of the infiltration function to realize the sorting.

2. Example

Initial sequence: 46,79,56,38,40,84

Build heap:

Swap, kicking the maximum number out of the heap

And so on: The last two remaining nodes in the heap are exchanged, kicked out, and sorted.

3. Algorithm implementation:

 Public classHeapsort { Public Static voidMain (string[] args) {int[] a={49,38,65,97,76,13,27,49,78,34,12,64}; intArraylength=a.length; //Loop Build Heap         for(inti=0;i<arraylength-1;i++){              //Build a heapBuildmaxheap (a,arraylength-1-i); //swap heap top and last elementSwap (a,0,arraylength-1-i);          System.out.println (Arrays.tostring (a)); }      }    //build a large top heap from 0 to lastindex for the data array     Public Static voidBuildmaxheap (int[] Data,intLastIndex) {         //starting at the parent node of the lastindex node (the last node)         for(intI= (lastIndex-1)/2;i>=0;i--){            //K Save the node being judged            intk=i; //If the child node of the current K-node exists             while(k*2+1<=LastIndex) {                //index of the left child node of the K-node                intBiggerindex=2*k+1; //if Biggerindex is less than lastindex, that is, the right child node of the K node represented by biggerindex+1 exists                if(biggerindex<LastIndex) {                      //If the value of the right child node is large                    if(data[biggerindex]<data[biggerindex+1]){                          //Biggerindex always records the index of a larger child nodebiggerindex++; }                  }                  //if the value of the K-node is less than the value of its larger child nodes                if(data[k]<Data[biggerindex]) {                      //Exchange themswap (Data,k,biggerindex); //Assign the Biggerindex to K, start the next loop of the while loop, and re-guarantee that the value of the K-node is greater than the value of its left and right child nodesk=Biggerindex; }Else{                       Break; }              }        }    }    //Exchange    Private Static voidSwapint[] Data,intIintj) {inttmp=Data[i]; Data[i]=Data[j]; DATA[J]=tmp; } }

Bubble sort, quick sort to view: http://www.cnblogs.com/0201zcr/p/4763806.html

Select Sort, insert sort, hill sort to view: http://www.cnblogs.com/0201zcr/p/4764427.html

Thanks: Thank you for your patience and reading!

Eight kinds of sorting algorithms that must be known "Java Implementation" (c) Merge sort algorithm, heap sorting algorithm detailed

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.