归并排序
思想:采用分治思想。
分:将要排序的数组划分成长度为1的小数组
治:合并小数组进行排序
代码:
package com.practice;
import java.util.Arrays;
public class GuiBingSort {
public static void main(String[] args) {
int[] array = new int[]{3, 2, 6, 5, 9, 8, 0, 7};
int[] temp = new int[array.length];//创建一个临时数组用来存储排好序的元素
GBSort( array, 0, array.length-1, temp );
System.out.println(Arrays.toString( array ) );
}
//分:将数组分成长度为一的小数组
private static void GBSort(int[] array, int left, int right, int[] temp) {
if (left < right) {
int mid = (left + right) / 2;
GBSort( array, left, mid, temp );
GBSort( array, mid + 1, right, temp );
merge( array, left, mid, right,temp );
}
}
//治:对分好组的子序列进行排序
private static void merge(int[] array, int left, int mid, int right,int[] temp) {
int i = left;
int j = mid + 1;
int k=0;
while (i<=mid&&j<=right){
if(array[i]<=array[j]){
temp[k++]=array[i++];
}else{
temp[k++]=array[j++];
}
}
while (i<=mid) {
temp[k++]=array[i++];
}
while (j<=right){
temp[k++]=array[j++];
}
k=0;
while (left<=right){
array[left++]=temp[k++];
}
}
}