quick select

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;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章