数组:
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] arr=new int[]{8,3,5,9,1,7,3,10,22,41};
mergeSort(arr);
System.out.println(Arrays.toString(arr));
}
private static void mergeSort(int[] arr){
if(arr.length>1){
int[] half1 = new int[arr.length/2];
int[] half2 = new int[arr.length - arr.length/2];
System.arraycopy(arr, 0, half1, 0, arr.length/2);
System.arraycopy(arr, arr.length/2, half2, 0, arr.length - arr.length/2);
mergeSort(half1);
mergeSort(half2);
merge(half1,half2,arr);
}
}
private static void merge(int[] half1,int[] half2,int[] arr){
int current1 = 0,current2 = 0,current3 = 0;
while(current1 < half1.length && current2 < half2.length){
if(half1[current1] < half2[current2]){
arr[current3++] = half1[current1++];
}else{
arr[current3++] = half2[current2++];
}
}
while(current1 < half1.length)
arr[current3++]=half1[current1++];
while(current2 < half2.length)
arr[current3++]=half2[current2++];
}
}
链表:
import java.util.Collections;
import java.util.LinkedList;
public class LinkedListMerge {
public static void main(String[] args) {
LinkedList list = new LinkedList();
for(int i = 0;i<1000;i++){
list.add(i);
}
Collections.shuffle(list);
System.out.println(list);
mergeSort(list);
System.out.println(list);
}
public static void mergeSort(LinkedList list){
if(list.size()>1){
LinkedList half1 = new LinkedList();
LinkedList half2 = new LinkedList();
while(list.size()>0){
half1.add(list.poll());
if(list.size()>0){
half2.add(list.removeLast());
}
}
mergeSort(half1);
mergeSort(half2);
merge(half1,half2,list);
}
}
//这个合并方法是比较优雅的,非常容易理解
public static void merge(LinkedList list1,LinkedList list2,LinkedList result){
while(list1.peek()!=null && list2.peek()!=null){
if(list1.peek() > list2.peek()){
result.add(list2.poll());
}else{
result.add(list1.poll());
}
}
while(list1.peek()!=null){
result.add(list1.poll());
}
while(list2.peek()!=null){
result.add(list2.poll());
}
}
}
几乎一样,但是链表的更加优雅一些。