import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 将给定数组排序 * @param arr int整型一维数组 待排序的数组 * @return int整型一维数组 */ public int[] MySort (int[] arr) { // write code here if (arr == null || arr.length < 1) { return new int[0]; } //quickSort(arr); // heapSort(arr); mergeSort(arr); return arr; } public void quickSort(int[] arr) { quickSort(arr, 0, arr.length - 1); } private void quickSort(int[] arr, int left, int right) { if (left < right) { int mid = partition(arr, left, right); quickSort(arr, left, mid - 1); quickSort(arr, mid + 1, right); } } private int partition(int[] arr, int left, int right) { int tmp = arr[left]; while (left < right) { while (left < right && arr[right] >= tmp) { right--; } arr[left] = arr[right]; while (left < right && arr[left] <= tmp) { left++; } arr[right] = arr[left]; } arr[left] = tmp; return left; } public void heapSort(int[] arr) { int n = arr.length; for (int i = n / 2 - 1; i >= 0; i--) { adjustHeap(arr, i, n); } for (int j = n - 1; j >= 0; j--) { int tmp = arr[j]; arr[j] = arr[0]; arr[0] = tmp; adjustHeap(arr, 0, j); } } private void adjustHeap(int[] arr, int i, int len) { int tmp = arr[i]; for (int k = 2 * i + 1; k < len; k = 2 * k + 1) { if (k + 1 < len && arr[k] < arr[k + 1]) { k++; } if (arr[k] > tmp) { arr[i] = arr[k]; i = k; } else { break; } } arr[i] = tmp; } public void mergeSort(int[] arr) { mergeSort(arr, 0, arr.length - 1); } private void mergeSort(int[] arr, int left, int right) { if (left < right) { int mid = left + (right - left) / 2; mergeSort(arr, left, mid); mergeSort(arr, mid + 1, right); merge(arr, left, mid, right); } } private void merge(int[] arr, int left, int mid, int right) { int[] tmp = new int[right - left + 1]; int i = left; int j = mid + 1; int k = 0; while (i <= mid && j <= right) { if (arr[i] <= arr[j]) { tmp[k++] = arr[i++]; } else { tmp[k++] = arr[j++]; } } while (i <= mid) { tmp[k++] = arr[i++]; } while (j <= right) { tmp[k++] = arr[j++]; } k = 0; i = left; while (k < tmp.length) { arr[i++] = tmp[k++]; } } }