java快速排序

来源:互联网 发布:甘肃省精准扶贫大数据 编辑:程序博客网 时间:2024/06/11 02:50

O(nlog(n)时间和O(logn)的栈空间

package contcurrentandalgorithm;

/**
 *
 * @author Administrator
 *
zyyjiao@mail.ustc.edu.cn
 */
public class QSort {

    public static void main(String[] args) {
        int a[] = {3, 4, 2, 1, 6, 5, 7, 8};
        qSort(a, 0, 7);
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }

    public static void qSort(int a[], int left, int right) {

        int i = left;
        int j = right;
        int temp = a[i];
        if (left >= right) {
            return;
        }
        while (i < j) {
            while (i < j && temp < a[j]) {
                j--;

            }
            a[i] = a[j];
            while (i < j && temp > a[i]) {
                i++;

            }
            a[j] = a[i];

        }

        a[i] = temp;
        qSort(a, left, j - 1);
        qSort(a, j + 1, right);


    }
}