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*/PublicStaticInt[] Sort (Int[] Nums,int Low,IntHigh) {int mid = (low + high)/2;if (Low <High) {//LeftSort (nums, low, mid);//Right sort (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*/PublicStaticvoid Merge (Int[] Nums,int Low,int Mid,IntHigh) {int[] Temp =NewInt[high-low + 1];int i = low;//Left pointerInt J = mid + 1;//Right pointerint k = 0;//Move the smaller number first to the new arraywhile (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++];} //for ( Span style= "COLOR: #0000ff" >int k2 = 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:

PublicClassHeapsort {PublicStaticvoidMain (string[] args) {Int[] A={49,38,65,97,76,13,27,49,78,34,12,64};int arraylength=A.length;//Loop Build HeapForint i=0;i<arraylength-1;i++){//Build Heap Buildmaxheap (a,arraylength-1-i);//Swap heap top and last element swap (a,0,arraylength-1-i); System.out.println (Arrays.tostring (a)); } }//Build a large top heap from 0 to lastindex for the data arrayPublicStaticvoid Buildmaxheap (int[] Data,IntLastIndex) {//Starting at the parent node of the lastindex node (the last node)Forint i= (lastIndex-1)/2;i>=0;i--){//K Save the node being judgedint k=I//If the child node of the current K-node existswhile (k*2+1<=LastIndex) {//Index of the left child node of the K-nodeint biggerindex=2*k+1;//If Biggerindex is less than lastindex, that is, the right child node of the K node represented by biggerindex+1 existsif (biggerindex<LastIndex) {//If the value of the right child node is largeif (data[biggerindex]<data[biggerindex+1]){//Biggerindex always records the index of a larger child node biggerindex++; } }//If the value of the K-node is less than the value of its larger child nodesif (data[k]<Data[biggerindex]) {//Exchange them swap (data,k,biggerindex); // give the Biggerindex to K, start the next loop of the while loop, Re-guarantee that the value of the K-node is greater than the value of its left and right child nodes K=BIGGERINDEX;} else{break; }}}} // interchange private static void swap (int[] data, int I, int j) {int tmp=data[i"; Data[i]=data[j]; data[j]=TMP; } } 

Eight kinds of sorting algorithms you must know "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.