Websultanate Task

mail@pastecode.io avatar
unknown
plain_text
6 months ago
1.1 kB
2
Indexable
Never
function merge(left, right) {
    const result = [];
    let leftIndex = 0;
    let rightIndex = 0;
    while (leftIndex < left.length && rightIndex < right.length) {
        if (left[leftIndex] > right[rightIndex]) {
            result.push(left[leftIndex]);
            leftIndex++;
        } else {
            result.push(right[rightIndex]);
            rightIndex++;
        }
    }

    return result.concat(left.slice(leftIndex), right.slice(rightIndex));
}

function mergeSort(arr) {
    if (arr.length <= 1) return arr;

    const middle = Math.floor(arr.length / 2);
    const left = arr.slice(0, middle);
    const right = arr.slice(middle);

    return merge(mergeSort(left), mergeSort(right));
}

function findKthLargest(arr, k) {
    if (k < 1 || k > arr.length) {
        return "Invalid k value";
    } else if(arr.length === 1){
      return arr[0]
    }

    const sortedArray = mergeSort(arr);

    return sortedArray[arr.length - k];
}

const numbers = [3, 1, 4, 1, 5, 9, 2, 6];
const k = 2;
console.log(`The ${k}th largest element is: ${findKthLargest(numbers, k)}`);