快速排序非递归版(利用键值对)

23 阅读1分钟
    // 建立一个函数

    public static void quickSort(int [] array) {

            LinkedList<int[]> list = new LinkedList<int[]>();   // 用来保存待处理的范围

            int start = 0;

            int end = array.length - 1;

           list.add(new int[]{start, end});

          while (list.size() > 0) {

              int [] range = list.getFirst();

              int s = range[0];

              int e = range[1];

              int temp = array[s];

          while (s < e) {
            while (s < e && temp < array[e]) {
                e--;
            }
            if (s == e) {
                break;
            }
            array[s++] = array[e];
            while (s < e && temp > array[s]) {
                s++;
            }
            if (s == e) {
                break;
            }
            array[e--] = array[s];
        }
        array[s] = temp;

        if (range[0] < s - 1) {

           list.add(new int[]{start, s - 1});

        }

        if (s + 1 < range[1]) {

          list.add(new int[]{s + 1, end});

       }

      list.removeFirst();

    }

}