Skip to content

Instantly share code, notes, and snippets.

@revanth0212
Last active April 21, 2018 19:46
Show Gist options
  • Select an option

  • Save revanth0212/7b74039eb663e59bb7a5cddebcc0df99 to your computer and use it in GitHub Desktop.

Select an option

Save revanth0212/7b74039eb663e59bb7a5cddebcc0df99 to your computer and use it in GitHub Desktop.
Quick Select. Also can be termed as Finding Kth Smallest Element in Unsorted array with no duplicates.
function swap(arr, i, j) {
var temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
return arr
}
function partition(arr, start, end) {
var pivot = end
while(start <= end) {
if (arr[start] < arr[pivot]) {
start++
} else if (arr[end] > pivot) {
end--
} else {
swap(arr, start, end)
start++
end--
}
}
swap(arr, start, pivot)
return start
}
function quickSort(arr, start, end) {
if (end > start) {
var newPivot = partition(arr, start, end)
quickSort(arr, start, newPivot-1)
quickSort(arr, newPivot+1, end)
}
}
function quickSelect(arr, k, start, end) {
if (end > start) {
var pivot = partition(arr, start, end)
if (pivot === k-1) {
return arr[pivot]
} else if (k-1 < pivot) {
return quickSelect(arr, k, start, pivot-1)
} else if (k-1 > pivot) {
return quickSelect(arr, k, pivot+1, end)
}
}
}
function select(arr, k) {
quickSelect(arr, k, 0, arr.length-1)
}
function findKthSmallestElement(arr, k) {
quickSelect(arr, k, 0, arr.length-1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment