MergeSort
Merge sort is an O(n log n) comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Merge sort is a divide and conquer algorithm that was invented by John von Neumann in 1945.
Conceptually, a merge sort works as follows
- Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
- Repeatedly merge sublists to produce new sublists until there is only 1 sublist remaining. This will be the sorted list
<Introduction to algorithm>
The merge sort algorithm closely follows the divide-and-conquer paradigm. Intuitively,
it operates as follows.
Divide: Divide the n-element sequence to be sorted into two subsequences of n=2
elements each.
Conquer: Sort the two subsequences recursively using merge sort.
Combine: Merge the two sorted subsequences to produce the sorted answer
View Code
1 /* 2 * Best Average Worst Memory Stable 3 * nlogn nlogn nlogn n Yes 4 */ 5 public class MergeSort { 6 7 public static int[] sort(int[] a){ 8 if(a.length>1){ 9 int leftLength=a.length/2; 10 int rightLength=a.length - leftLength; 11 12 int[] left=new int[leftLength]; 13 int[] right=new int[rightLength]; 14 System.arraycopy(a, 0, left, 0, leftLength); 15 System.arraycopy(a, leftLength, right, 0, rightLength); 16 17 left=sort(left); 18 right=sort(right); 19 20 int i=0; 21 int j=0; 22 for(int k=0;k<a.length;k++){ 23 if(i<leftLength && j==rightLength){ 24 a[k]=left[i]; 25 i++; 26 } 27 else if(j<rightLength && i==leftLength){ 28 a[k]=right[j]; 29 j++; 30 } 31 else if(i<leftLength && j<rightLength){ 32 if(left[i]<=right[j]){ 33 a[k]=left[i]; 34 i++; 35 } 36 else{ 37 a[k]=right[j]; 38 j++; 39 } 40 } 41 } 42 } 43 return a; 44 } 45 46 public static void printArray(int[] a){ 47 for(int i = 0;i < a.length;i++){ 48 System.out.print(a[i]+" "); 49 } 50 } 51 52 public static void main(String[] args) { 53 int[] a=new int[]{2, 1, 5, 4, 9, 8, 6, 7, 10, 3}; 54 sort(a); 55 printArray(a); 56 57 } 58 59 }

浙公网安备 33010602011771号