快速排序
public class quickSort {
public static void main(String[] args) {
int[] arr = {4, 6, 2, 9, 0, 1, 5};
quickSort(arr,0, arr.length - 1);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
//s是起点 e是终点
static void quickSort(int[] array, int s, int e) {
if (s >= e) {
return;
}
int start = s;
int end = e;
//从头部的第一个值做为基准值
int temp = array[start];
while(start < end) {
//把比基准值小的保存到头部
while (start < end && temp < array[end]) {
end--;
}
if (start < end) {
array[start] = array[end];
start++;
}
//从头部找比基准值大的
while(start < end && temp > array[start]) {
start++;
}
//把比基准值大的保存到尾部
if (start < end) {
array[end] = array[start];
end--;
}
}
//头部跟尾部重合,找到基准值的位置
//start==end
array[start] = temp;
//头部数组递归调用
quickSort(array, s, start - 1);
quickSort(array, start + 1, e);
}
}

浙公网安备 33010602011771号