编辑代码

public class lianxi {

    // 根据基准值进行分区
    public static int partition(int[] array, int arrStart, int arrEnd, int pivoPos) {
        int ItpivotValueCount = 0;
        int temp;
        int pivotValue = array[pivoPos];
        temp = array[pivoPos];
        array[pivoPos] = array[arrEnd - 1];
        array[arrEnd - 1] = temp;
        for (int i = arrStart; i < arrEnd - 1; ++i) {
            if (array[i] < pivotValue) {
                temp = array[arrStart + ItpivotValueCount];
                array[arrStart + ItpivotValueCount] = array[i];
                array[i] = temp;
                ++ItpivotValueCount;
            }
        }
        temp = array[arrEnd - 1];
        array[arrEnd - 1] = array[arrStart + ItpivotValueCount];
        array[arrStart + ItpivotValueCount] = temp;
        pivotValue = array[arrStart + ItpivotValueCount];
        return ItpivotValueCount + arrStart;

    }

    // 返回基准值在数组里面的位置
    static int findPivotPos(int[] array, int arrStart, int arrEnd) {
        return arrStart;
    }

    // 修改quickSort方法,仅对包含第K大元素的那一侧进行递归排序
    public static boolean quickSort(int[] array, int arrStart, int arrEnd, int k) {
        if (arrEnd - arrStart < 2) {
            return false;
        }
        int pivotPos = findPivotPos(array, arrStart, arrEnd);
        int partition = partition(array, arrStart, arrEnd, pivotPos);

        // 只对包含第K大元素的那一侧进行递归排序
        if (partition == k) {
            return true;
        } else if (partition < k) {
            return quickSort(array, partition + 1, arrEnd, k);
        } else {
            return quickSort(array, arrStart, partition, k);
        }
    }

    public static void main(String[] args) {
        int[] array = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
        int k = 4; // 例如,查找第3大元素
        quickSort(array, 0, array.length, k);
        System.out.println("第" + k + "大元素是: " + array[k - 1]);
    }
}