归并排序
需求:
排序前:{8,4,5,7,1,3,6,2}
排序后:{1,2,3,4,5,6,7,8}
算法设计
Merge类:
package suanfa;
public class Merge {
private static Comparable[] assist;
private static boolean less(Comparable v,Comparable w){
return v.compareTo(w)<0;
}
private static void exch(Comparable[] a,int i,int j){Comparable t = a[i];a[i] =a[j];a[j] =t;
}public static void sort(Comparable[] a){assist = new Comparable[a.length];int lo=0;int hi=a.length-1;sort(a,lo,hi);
}
private static void sort(Comparable[] a,int lo,int hi){if(hi<= lo){return;}int mid = lo+(hi-lo)/2;sort(a,lo,mid);sort(a,mid+1,hi);merge(a,lo,mid,hi);
}
private static void merge(Comparable[] a,int lo,int mid,int hi){int i =lo;int p1 =lo;int p2 =mid+1;while(p1<=mid&&p2<=hi) {if (less(a[p1], a[p2])) {assist[i++] = a[p1++];} else {assist[i++] = a[p2++];}}while (p1<=mid){assist[i++]=a[p1++];}while (p2<=hi){assist[i++]=a[p2++];}for(int index=lo;index<=hi;index++){a[index]=assist[index];}}
}
MergeTest类:
package suanfa;
import java.util.Arrays;
public class MergeTest {
public static void main(String[] args) {
Integer[] a={8,4,5,7,1,3,6,2};
Merge.sort(a);
System.out.println(Arrays.toString(a));
}
}
录制: untitled2 – Merge.java
录制文件:https://meeting.tencent.com/crm/K0oDw6L726