Last active
April 21, 2018 19:43
-
-
Save revanth0212/dd8472f98ddb9aa2f76ae86e444b9669 to your computer and use it in GitHub Desktop.
Find Kth Largest Element in an Unsorted array with no duplicates.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 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 findKthLargest(nums, k) { | |
| return quickSelect(nums, nums.length + 1 - k, 0, nums.length-1) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment