# Three sorting algorithms (merge sort, quick sort, heap sort)

Source: Internet
Author: User

Merge sort: An efficient sorting algorithm based on the merging operation, which is a very typical application of divide-and-conquer method (Divide and Conquer). The ordered Subsequence is merged to obtain a fully ordered sequence, i.e., the order of each subsequence is ordered, and then the sequence of sub-sequences is ordered. If two ordered tables are combined into an ordered table, they are called two-way merging.
The merge sort algorithm is stable, the array needs O (n) extra space, the list needs O (log (n)) extra space, time complexity is O (Nlog (n)), the algorithm is not adaptive, does not require random reading of the data.

``工作原理：1、申请空间，使其大小为两个已经排序序列之和，该空间用来存放合并后的序列2、设定两个指针，最初位置分别为两个已经排序序列的起始位置3、比较两个指针所指向的元素，选择相对小的元素放入到合并空间，并移动指针到下一位置4、重复步骤3直到某一指针达到序列尾5、将另一序列剩下的所有元素直接复制到合并序列尾``

Code implementation:

`` Public classMain { Public Static void Sort(int[]arr,intLeft,intright) {if(Left>=right) {return; }intMiddle = (left+right)/2;        Sort (arr,left,middle); Sort (arr,middle+1, right);    Merge (Arr,left,middle,right); }Private Static void Merge(int[] arr,intLeftintMiddle,intright) {int[] temparr=New int[Arr.length];intArrindex=left;intArr2left = Middle+1;intArr1left = left; while(Arr1left<=middle&&arr2left<=right) {if(Arr[arr1left]<=arr[arr2left])            {temparr[arrindex++]=arr[arr1left++]; }Else{temparr[arrindex++]=arr[arr2left++]; }        } while(Arr1left<=middle)        {temparr[arrindex++]=arr[arr1left++]; } while(Arr2left<=right)        {temparr[arrindex++]=arr[arr2left++]; } for(inti=left;i<=right;i++) {Arr[i]=temparr[i]; }    }Static voidPrintarr (int[] arr) {System. out. Print ("{"); for(intI:arr) {System. out. Print (i+" "); } System. out. Print ("}"); } Public Static void Main(string[] args) {intarr[]=New int[]{9,3,6,4,7,1,0,2,5}; Sort (arr,0, arr.length-1);    Printarr (arr); }}``

Output Result:

``{0 1 2 3 4 5 6 7 9 }``

Quick sort: Quick sort (Quicksort) is an improvement to the bubbling sort. By sorting the sorted data into separate two parts, one part of all data is smaller than the other part of the data, and then the two parts of the data are quickly sorted by this method, the entire sorting process can be recursive, so as to achieve the entire data into an ordered sequence.

``工作原理①以第一个关键字 K 1 为控制字，将 [K 1 ,K 2 ,…,K n ] 分成两个子区，使左区所有关键字小于等于 K 1 ，右区所有关键字大于等于 K 1 ，最后控制字居两个子区中间的适当位置。在子区内数据尚处于无序状态。 ②把左区作为一个整体，用①的步骤进行处理，右区进行相同的处理。（即递归）③重复第①、②步，直到左区处理完毕。``

Code implementation:

`` Public classMain { Public Static void PrintArray(int[] array) {System. out. Print ("{"); for(intI:array) {System. out. Print (i+" "); } System. out. Print ("}"); } Public Static int partion(int[] arr,intLeftintright) {intX=arr[left];intI=left;intJ=right; while(I&LT;J) { while(I<j && arr[j]>=x)            {j--; }if(I&LT;J)            {ARR[I]=ARR[J]; } while(I<j && arr[i]<=x)            {i++; }if(I&LT;J)            {Arr[j]=arr[i]; }} arr[i]=x;returnI } Public Static void QuickSort(int[]arr,intLeftintright) {intI=0;if(Left<right)            {i=partion (arr,left,right); QuickSort (arr,left,i-1); QuickSort (arr,i+1, right); }    } Public Static void Main(string[] args) {intarr[]={3, \$,7,8,2,9,0,4,2,8,9,1}; QuickSort (arr,0, arr.length-1);    PrintArray (arr); }}``

Output Result:

``{0 1 2 2 3 4 7 8 8 9 9 46 }``

Heap sorting: Heap is an important data structure for a completely binary tree, the bottom layer if the data is stored in an array, suppose that an element is ordinal I (Java array starting from 0, I is 0 to n-1), if it has left dial hand tree, then Zuozi position is 2i+1, if there is a right subtree, the right subtree position is 2i+ 2, if there is a parent node, the position of the parent node is (n-1)/2 rounding. is divided into the largest heap and the smallest heap, the maximum heap of any child tree root node is not less than any child nodes, the minimum heap root node is not greater than any child nodes. The so-called heap ordering is to use the heap data structure to sort the array, we use the largest heap. The thought of handling and the bubbling sort, the selection sort is very similar, a layer is capped, but the largest element is selected using the largest heap. The largest element of the maximum heap must be placed in the No. 0 position, after the heap is built, Exchange 0 positions element and the top. Heap sorting is in-situ sorting (small space), and the worst run time is O (N2), which is the asymptotic optimal comparison sorting algorithm.

``工作原理：1.构建最大堆。2.选择顶，并与第0位置元素交换3.由于步骤2的的交换可能破环了最大堆的性质，第0不再是最大元素，需要调用maxHeap调整堆(沉降法)，如果需要重复步骤2堆排序中最重要的算法就是maxHeap，该函数假设一个元素的两个子节点都满足最大堆的性质(左右子树都是最大堆)，只有跟元素可能违反最大堆性质，那么把该元素以及左右子节点的最大元素找出来，如果该元素已经最大，那么整棵树都是最大堆，程序退出，否则交换跟元素与最大元素的位置，继续调用maxHeap原最大元素所在的子树。该算法是分治法的典型应用。``

Code implementation:

`` Public classMain { Public Static voidPrintArray (int[]Array) {System.out.print ("{"); for(intIArray) {System.out.print (i+" "); } System.out.println ("}"); } Public Static voidExchangeint[]Array,intIndex1,intINDEX2) {inttemp =Array[INDEX1];Array[Index1] =Array[Index2];Array[INDEX2] = temp; } Public Static voidMain (string[] args) {int Array[] ={9, -,7,6, the,4,3, A,1,Ten,-1,- +,-3,0}; System.out.println ("before heap:"); PrintArray (Array); Heapsort (Array); System.out.println ("After heap sort:"); PrintArray (Array); } Public Static voidHeapsort (int[]Array){if(Array==null | |Array. length<=1){return; }//Jian YuBuildmaxheap (Array);//Sort, put the maximum value one at a back         for(intI=Array. length-1; I>0; i--) {Exchange (Array,0, i);//Recovery heapMaxheap (ArrayI0); }    } Public Static voidBuildmaxheap (int[]Array){if(Array= = NULL | |Array. length<=1) {return; }intHalf =Array. length/2; for(inti=half-1; i>=0; i--) {Maxheap (Array,Array. length,i); }    } Public Static voidMaxheap (int[]Array,intHeapSize,intIndex) {intLeft = index *2+1;intright = Index *2+2;intlargest = index;if(LeftArray[left]>Array[index])        {largest = left; }if(RightArray[right]>Array[Largest])        {largest = right; }if(Index! = largest) {Exchange (Array, index, largest); Maxheap (Array, heapsize,largest); }    }}``

Output Result:

``Before heap:{9 18 7 6 15 4 3 12 1 10 -1 -21 -3 0 }After heap sort:{-21 -3 -1 0 1 3 4 6 7 9 10 12 15 18 }``

Three sorting algorithms (merge sort, quick sort, heap sort)

Related Keywords:

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.