归并排序是标准java类库中泛型排序所使用的算法:分治策略--》
基本思路:
1.将大数组用递归手段拆分成小数组。
2.对小数组进行排序。
3.合并排序过的小数组。
原始数组::12 15 10 88 8 6 4
1.拆分:
【12 15 10 88】 【8 6 4】
【12 15】 【10 88】
【12】 【15】 【10】 【88】
2.对小数组进行排序,然后合并:
【12】 【15】 --》【12 15】
【10】 【88】 --》【10 88】
【12 15】【10 88】--》【10 12 15 88】
...........
java归并排序代码实现:
public static void sort(int[]array,int left,int right){
//只要是小数组的size>=2,则继续分而治之...
if (left<right) {
int center = (left+right)/2;
//左侧递归
sort(array, left, center);
//右侧递归
sort(array, center+1, right);
//合并左右侧
merge(array, left, center, right);
}
}
private static void merge(int[]array,int left,int center,int right){
int before = left;
int after = center+1;
int index = left;
int tmp = left;
//临时数组
int []tempArray = new int[array.length];
//合并小数组:都从小数组从前往后遍历,把较小的放到临时数组中...
while(before<=center&&after<=right)
{
if (array[before]<=array[after]) {
tempArray[index++] = array[before++];
}
else{
tempArray[index++] = array[after++];
}
}
//如果右侧小数组已全部合并完,则把左侧小数组全部放到临时数组后方
while(before<=center){
tempArray[index++] = array[before++];
}
//如果左侧小数组已全部合并完,则把右侧小数组全部放到临时数组后方
while(after<=right){
tempArray[index++] = array[after++];
}
//把临时数组排好序的元素依次转移到原始数组...
for (int i = left; i <= right; i++) {
array[i] = tempArray[i];
}
}