快速排序它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。 步骤: 1、先从一串数中取第一个做为指标 2、然后用它从数组后面开始比较,如果比他大,继续向前比较,直到找到比它小的然后交换位置 3、然后又从前面开始比较,找到比他大的交换位置,这样来回比较,直到所有数都比完 4、然后再分别解决这个标记数左边和右边的数
代码如下:有点小复杂
public class QuickSort2 {
public static void main(String[] args) {
int[] num = new int[]{1, 1, 3, 44, 12, 32, 15, 24, 66, 98, 7, 10, 55, 70};
int top = 0;
int down = num.length - 1;
qSort(num, top, down);
for (int i : num) {
System.out.print(i + " ");
}
}
public static void qSort(int[] num, int top, int down) {
if (top >= down) {
return;
}
int start = top;//起始位置
int end = down;//结束位置
int temp = num[start];//选取标记数
while (start < end) {
//从后面开始比
for (int i = end; i >= start; i--) {
if (temp < num[i]) {
end--;
} else {
int t = num[start];
num[start] = num[end];
num[end] = t;
temp = num[end];
start++;
break;
}
}
//从前面开始比
for (int i = start; i <= end; i++) {
if (temp > num[i]) {
start++;
} else {
int t = num[start];
num[start] = num[end];
num[end] = t;
temp = num[start];
end--;
break;
}
}
}
//左边
if (top < start) {
qSort(num, top, start - 1);
}
//右边
if (end < down) {
qSort(num, end + 1, down);
}
}
}