Skip to main content

Find K Largest element

// Find kth largest element in an array
export function findKthLargest(a: number[], k: number): number {
const i = a.length - k
if (i < 0 || i >= a.length) {
// out of range
return Infinity
}
find(a, 0, a.length - 1, i)
return a[i]
}

function swap(a: number[], i: number, j: number) {
const tmp = a[i]
a[i] = a[j]
a[j] = tmp
}

function find(a: number[], low: number, high: number, i: number): number {
if (low === high) return low

const pi = partition(a, low, high)
if (pi === i) return pi
if (pi > i) return find(a, low, pi-1, i)
return find(a, pi+1, high, i)
}

function partition(a: number[], low: number, high: number): number {
const pivot = a[high]

// find first position i where a[i] >= pivot (could be pivot position itself)
let i = low
while (a[i] < pivot) {
i++
}

// up to the position prior to the pivot, if found element smaller than pivot then move it to the left
for (let j = i + 1; j < high; j++) {
if (a[j] < pivot) {
swap(a, i, j)
i++
}
}

// swap pivot with i
if (i < high) swap(a, i, high)

return i
}