归并的思想就是分治.时间复杂度..忘记了
大概实现了下..还真挺费劲的...
很受打击啊...还有什么好的排序算法..大家给推荐下我试着弄弄
没怎么写注释..以此作为我的备用.
这几天的思考中我终于发现..理解和会用和精通是两个概念..
学海无涯.人生苦短啊
public class Test1 {
public static void main(String[] args) {
int[] arr1 = { 4,23,234,3,41,311,3,5 ,56,5,46};
int[] arr2 = { 4,23,234,3,41,311,3,5 ,56,5,46};
Test1 test1 = new Test1();
test1.splitAndMerger(arr1, 0, arr1.length-1);
test1.printArray(arr1);
test1.printArray(arr2) ;
Arrays.sort(arr2) ;
test1.printArray(arr2) ;
}
public void splitAndMerger(int[] ints, int begin, int end) {
int mid = (begin + end) / 2;
if (end > begin) {
splitAndMerger(ints, begin, mid);
splitAndMerger(ints, mid + 1, end);
merger(ints, begin, mid, end);
}
}
public void merger(int[] ints, int begin, int mid, int end) {
int temp1 = 0;
int temp2 = 0;
int[] arr1 = Arrays.copyOfRange(ints, begin, mid+1);
int[] arr2 = Arrays.copyOfRange(ints, mid+1, end+1);
for (int i = begin; i <= end; i++) {
if (temp1 == arr1.length && temp2 == arr2.length) {
break;
}
if (temp1 == arr1.length) {
ints[i] = arr2[temp2];
temp2++;
continue;
}
if (temp2 == arr2.length) {
ints[i] = arr1[temp1];
temp1++;
continue;
}
if (arr1[temp1] > arr2[temp2]) {
ints[i] = arr2[temp2];
temp2++;
} else {
ints[i] = arr1[temp1];
temp1++;
}
}
}
public void printArray(int[] array) {
this.printArray(array, 0, array.length-1);
}
public void printArray(int[] array, int begin, int end) {
for (int i = begin; i <= end; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}