算法系列之<快速排序>

快速排序:

 /**
     * 快速排序
     * 最好情况下:每趟把原序列分成两个长度几乎相等的子序列
     * 最差情况下:每趟把原序列分成长度相差很大的两个子序列
     * 平均时间复杂度:O(NLogN),空间复杂度O(logN)
     * case1:{1}
     * case2:{1,2}
     * case3:{1,2,3,4,5}
     * case4:{5,4,3,2,1}
     * case5:{8,9,10,2,3}
     * @param array1
     * @param low
     * @param high
     * @return
     */
    public static void quickSort(int[] array1,int n,int low,int high){
        if(low<high&&low>=0&&low<n&&high>=0&&high<n) {
            int vot = array1[low];
            int i = low;
            int j = high;
            while(i<j) {
                while (j > i && array1[j] > vot) {
                    j--;
                }
                if (j > i) {
                    if (array1[j] < vot) {
                        int temp = array1[j];
                        array1[i] = temp;
                        i++;
                    }
                }

                while (i < j && array1[i] <= vot) {
                    i++;
                }
                if (i < j) {
                    if (array1[i] > vot) {
                        int temp = array1[i];
                        array1[j] = temp;
                        j--;
                    }
                }
            }
            if(i==j){
                array1[i]=vot;
            }


            quickSort(array1, array1.length,low, j - 1);
            quickSort(array1, array1.length,i + 1, high);
            }

    }

猜你喜欢

转载自www.cnblogs.com/zhaijing/p/9775748.html
今日推荐