# 归并排序

public class Merge {
private int[] A = {2,6,7};
private int[] B = {1,3,4,5,8,9,10};
private int[] C = new int[10];

public void sort(){
int a = 0;
int b = 0;
int c = 0;
while(a < A.length && b < B.length){
if(A[a] < B[b])
C[c++] = A[a++];
else
C[c++] = B[b++];
}
while(a < A.length)
C[c++] = A[a++];
while(b < B.length)
C[c++] = B[b++];
}

public void display(){
for(int i = 0 ; i < C.length ; i++){
System.out.print(C[i] + " ");
}
System.out.print("\n");
}

public static void main(String[] args) {
Merge m = new Merge();
m.sort();
m.display();
}
}

1 2 3 4 5 6 7 8 9 10

public class MergeSort {
private int[] data;

public MergeSort(int[] data){
this.data = data;
}

public void sort(){
int[] temp = new int[data.length];
this.sort(temp, 0, data.length - 1);
}

private void sort(int[] ints,int first,int last){
if(first == last)
return;
int middle = (last + first)/2;
this.sort(ints, first, middle);
this.sort(ints, middle + 1, last);
this.merge(ints, first, middle , last);
}

private void merge(int[] ints,int first,int middle,
int last){
System.out.println(first+" "+last);
int i = first;
int a = first;
int b = middle  + 1;
while(a <= middle && b <= last){
if(data[a] < data[b])
ints[i++] = data[a++];
else
ints[i++] = data[b++];
}
while(a <= middle)
ints[i++] = data[a++];
while(b <= last)
ints[i++] = data[b++];
for(i = first ; i < last + 1 ; i++){
data[i] = ints[i];
}
}

public void display(){
for(int i = 0 ; i < data.length ; i++){
System.out.print(data[i] + " ");
}
System.out.print("\n");
}

public static void main(String[] args) {
int[] a = {8, 6, 1, 4, 2, 7, 3, 5};
int[] b = {6, 5, 1, 4, 2, 7, 3};
MergeSort ms1 = new MergeSort(a);
MergeSort ms2 = new MergeSort(b);
ms1.sort();
ms1.display();
ms2.sort();
ms2.display();
}
}

0 1
2 3
0 3
4 5
6 7
4 7
0 7
1 2 4 6 7 3 5 8
0 1
2 3
0 3
4 5
4 6
0 6
1 2 3 4 5 6 7


ms1的归并过程如下图：

ms2的归并过程如下图：

posted @ 2014-04-13 22:42  心意合一  阅读(191)  评论(0编辑  收藏  举报