当前位置: 首页 > 工具软件 > Quick[select] > 使用案例 >

quick select

吴凯泽
2023-12-01

https://discuss.leetcode.com/topic/14611/java-quick-select


public static int quickselect(int[] arr, int k){

int start = 0, end = arr.length - 1, index = k - 1;

while(start < end){

int pivot = partition(arr, start, end);

if(pivot < index)

start = pivot + 1;

else if(pivot > index)

end = pivot - 1;

return arr[pivot];

}

return arr[start];

}


public static int partition(int[] arr, int left, int right){

int pivot;

while(left <= right){

while(left <=right && arr[left] <= arr[pivot])

left++;

while(left <= right && arr[right] > arr[pivot])

right--;

if(left > right) break;

swap(arr, left, right);

}

swap(pivot, right);

return right;

}

 类似资料:

相关阅读

相关文章

相关问答