快速排序

来源:互联网 发布:乔任梁死亡真相知乎 编辑:程序博客网 时间:2024/04/27 16:17
package Sort;


public class QuickSort {
public static void main(String[] args) {
int[] a = { 49, 38, 65, 97, 76, 13, 27, 49 };
quickSort(a, 0, 7);
print(a);
}


// 打印函数
public static void print(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}


// 分治递归
public static void quickSort(int[] numbers, int low, int high) {
if (low < high) {
int middle = getMiddle(numbers, low, high);
quickSort(numbers, low, middle - 1);
quickSort(numbers, middle + 1, high);
}
}


// 一次排序
public static int getMiddle(int[] a, int low, int high) {
int key = a[low];
while (low < high) {
while (low < high && a[high] >= key)
high--;
if (a[high] <= key) {
int tmp = a[high];
a[high] = a[low];
a[low] = tmp;
}
while (low < high && a[low] <= key)
low++;
if (a[low] >= key) {
int tmp = a[low];
a[low] = a[high];
a[high] = tmp;
}
}
return low;
}
}
0 0
原创粉丝点击