标签:span code ali string ima mic ges wrapper static
归并排序:利用分而治之的思想。
public static void merge(int[] arr, int left, int mid, int right){
int[] temp = new int[right - left + 1]; //新开一个临时数组存放每一代gap排好序的数组
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right){
if (arr[i] < arr[j]){
temp[k++] = arr[i++];
}else{
temp[k++] = arr[j++];
}
}
while (i <= mid){
temp[k++] = arr[i++];
}
while (j <= right){
temp[k++] = arr[j++];
}
for (int x = 0; x < k; x++){
arr[left+x] = temp[x];
}
}
public static void mergeSort(int arr[], int left, int right){
if (left < right){
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid+1, right);
merge(arr, left, mid, right);
}
}
int[] arr = {2, 4, 9, 3, 8, 6, 7, 1, 5};
mergeSort(arr, 0, 8);
for (int x : arr){
System.out.print(x + " ");
}
结果:
1 2 3 4 5 6 7 8 9
----- end -----
标签:span code ali string ima mic ges wrapper static
原文地址:https://www.cnblogs.com/denluoyia/p/9685841.html