i am trying to figure out how this code works.
function Kth_greatest_in_array(arr, k) {
for (let i = 0; i < k; i ) {
let max_index = i;
const tmp = arr[i];
for (let j = i 1; j < arr.length; j ) {
if (arr[j] > arr[max_index]) {
max_index = j;
}
}
arr[i] = arr[max_index];
arr[max_index] = tmp;
}
return arr[k - 1];
}
console.log(Kth_greatest_in_array([1,2,6,4,5], 3))
As you can see the goal is to find third biggest value. But i don know how the second loop works. Could you explain it to me step by step. For example, what is the meaning of veriable j, especially why they typed let j = i
CodePudding user response:
This method basically performs an in-place sort of the arr
array (but only "k" times - not a full sort), then returns the element (from the now partially sorted array) at index k-1
.
The inner for
loop looks through the remaining (unsorted) portion of the array to find the index of the item with the highest value:
if (arr[j] > arr[max_index]) {
max_index = j;
}
The specific statement you were asking about, let j = i 1
, means "declare a new variable, j
, and set its initial value to one greater than the current iteration of the outer for
loop". "j
" is arbitrary and could be any valid identifier, it's just often used by convention when you have nested for
loops since the outermost loop usually uses i
(which is presumably short for "index").
At the end of each iteration of the outer for
loop, these lines swap array elements so that this element is in the correct position:
arr[i] = arr[max_index];
arr[max_index] = tmp;
If you're curious to really understand the inner workings of a method like this, I'd highly encourage you to step through it with a debugger - it can be a great learning experience. Even just the tried-and-true method of sprinkling some temporary console.log
statements can help illuminate what's going on (e.g., print the state of arr
and max_index
after every outer and inner loop iteration).