Created
December 28, 2017 20:54
-
-
Save jianminchen/0173712e5664f4c65dbffb0c641ae589 to your computer and use it in GitHub Desktop.
JavaScript code - K shift away array - Peer wrote JavaScript code, and the code was written quickly as well.
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
function sortKMessedArray(arr, k) { | |
let minVal = Number.MAX_SAFE_INT; | |
for (let i = 0; i < arr.length; i++) { | |
for (let j = i + 1; j < (i + k + 1) && j < arr.length; j++) { | |
minVal = arr[i]; | |
if (arr[j] < minVal) { | |
[ arr[j], arr[i] ] = [ arr[i], arr[j] ]; | |
} | |
} | |
} | |
return arr; | |
} | |
const arr = [1, 4, 5, 2, 3, 7, 8, 6, 10, 9], k = 2 | |
console.log(sortKMessedArray(arr, 2)); | |
// => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
// K + 1 | |
// minimum 3, | |
// [1, 4, 5] -> 1 vs 4, min = 1, 1 vs 5 min = 1 | |
// [4, 5, 2] -> 4 vs 5, min = 4, 4 vs 2 min =2 , index = 2, swap index at index = 1 with index = 3 | |
// [4, 5] | |
// For each element of arr: looking k elements ahead | |
// Finding the minimum element from k range | |
// Swap first element with lowest element in range |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment