Last active
March 16, 2021 08:35
-
-
Save tin80122/79fbeb6451747c7dc1a48622df247256 to your computer and use it in GitHub Desktop.
LeetCode 215 Quick Sort space, Insert Sort
This file contains 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
//Topic: find Kth elements | |
//quick sort use space | |
var qsort = function(nums,k) { | |
if(nums.length <= 1) { | |
return nums | |
} | |
let leftAry = []; | |
let rightAry = []; | |
let pivot = nums[0]; | |
for(let i = 1; i < nums.length ; i++){ | |
nums[i] > pivot ? rightAry.push(nums[i]) : leftAry.push(nums[i]) | |
} | |
return qsort(leftAry).concat(pivot, qsort(rightAry)); | |
} | |
//native sort | |
var nativeSort = (nums,k) => { | |
nums.sort((a,b) => a-b) | |
return nums[nums.length - k] | |
} | |
const swap = (nums,a,b) => { | |
[nums[a],nums[b]] = [nums[b],nums[a]] | |
} | |
// insert sort | |
var insertSort = (nums,k) => { | |
for(let i = 1; i < nums.length; i++) { | |
let position = i; | |
while(position >= 0 && nums[position - 1] > nums[position]) { | |
swap(nums,position,position-1); | |
position--; | |
} | |
} | |
return nums[nums.length - k] | |
} | |
var findKthLargest = function(nums, k , sort) { | |
return sort(nums,k); | |
}; | |
const nums = [3,2,1,5,6,4]; | |
const k = 2; | |
console.log('qsort result:', findKthLargest(nums,k,qsort)[nums.length - k]); | |
console.log('nativeSort result:', findKthLargest(nums,k,nativeSort)) | |
console.log('insertSort result:', findKthLargest(nums,k,insertSort)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment