public class ArithmeticImpl implements Arithmetic {
@Resource
private QuickSort quickSort;
@Override
public void quickSort(int[] arr) {
quickSort.quickSort(arr);
}
}
public class QuickSort {
public void quickSort(int[] arr) {
quickSort(arr, 0, arr.length - 1);
}
private void quickSort(int[] arr, int left, int right) {
//核心递归函数
int pivot = 0;
int cutoff = 0;
int low = 0;
int high = 0;
if (cutoff <= right - left) {
pivot = median(arr, left, right);//如果元素充分多,进入快排 Pivot = Median3( A, Left, Right );
low = left;
high = right - 1;
while (true) {//将序列中比基准小的移到基准左边,大的移到右边
while (arr[++low] < pivot) ;
while (arr[--high] > pivot) ;
if (low < high) {
int temp = arr[low];
arr[low] = arr[high];
arr[high] = temp;
} else {
break;
}
int temp02 = arr[low];
arr[low] = arr[high - 1];
arr[high - 1] = temp02;
quickSort(arr, left, low - 1);
quickSort(arr, low + 1, right);
}
} else {
InsertionSort(arr); /* 元素太少,用简单排序 */
}
}
private int median(int[] arr, int left, int right) {
int Center = (left + right) / 2;
if (arr[left] > arr[Center])
swap(arr[left], arr[Center]);
if (arr[left] > arr[right])
swap(arr[left], arr[right]);
if (arr[Center] > arr[right])
swap(arr[Center], arr[right]);
/* 此时A[Left] <= A[Center] <= A[Right] */
swap(arr[Center], arr[right - 1]); /* 将基准Pivot藏到右边*/
/* 只需要考虑A[Left+1] … A[Right-2] */
return arr[right - 1]; /* 返回基准Pivot */
}
private void swap(int i, int j) {
int temp = i;
i = j;
j = temp;
}
private void InsertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];
int j = i;
for (j = i; j > 0 && arr[j - 1] > temp; j--) {
arr[j] = arr[j - 1];//初始值与第一个元素比较
}
arr[j] = temp;
}
}
}