快速排序

来源:互联网 发布:org.apache.http 报错 编辑:程序博客网 时间:2024/06/01 08:13
import java.util.Arrays;public class Test {    public static void main(String[] args) {        System.out.println("Hello World");        int[] a = {3, 5, 1, 2, 4, 5, 4, 3, 9, 0, 6};        int start = 0;        int end = a.length - 1;        new Test().fastSort(a, start, end);        System.out.println(Arrays.toString(a));    }    public void fastSort(int[] a, int low, int high) {        int start = low;//(为递归)记录开始值索引,记录结束值索引,关键值        int end = high;        int key = a[low];        //当初始索引和结束索引相等时,此时第一次循环比较结束,关键值的位置已经确定了。左边的值都比关键值小,右边的值都比关键值大,        while (end > start) {            while (end > start && a[end] >= key)  //从后向前比较,如果没有比关键值小的,比较下一个,直到有比关键值小的交换位置,然后又从前往后比较                end--;            if (a[end] < key) {                int temp = a[end];                a[end] = a[start];                a[start] = temp;            }            while (end > start && a[start] <= key)//从前往后比较,找出比关键值大的数值交换位置(把大值放在关键值之后)                start++;            if (a[start] > key) {                int temp = a[end];                a[end] = a[start];                a[start] = temp;            }        }        //递归        if (start > low) fastSort(a, low, start - 1);//左边序列。第一个索引位置到关键值索引-1        if (end < high) fastSort(a, end + 1, high);//右边序列。从关键值索引+1到最后一个    }}
原创粉丝点击