DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Question - Question 38

The task is to implement a selection sort that sorts an integer array in ascending order.

The boilerplate code:

function selectionSort(arr) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

The array is divided into 2 parts: The sorted part and the unsorted. For each position i, it assumes that arr[i] is the smallest of the unsorted part.

let minIndex = i
Enter fullscreen mode Exit fullscreen mode

The rest of the array is scanned to find the smallest element

for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }
Enter fullscreen mode Exit fullscreen mode

If the element found is smaller than arr[i], it swaps the value of arr[i] with the element.

 if (minIndex !== i) {
      [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
    }
Enter fullscreen mode Exit fullscreen mode

It continues until the array is fully sorted. The final code is

function selectionSort(arr) {
  // your code here
  for(let i = 0; i <arr.length - 1; i++) {
    let minIndex = i;

    for(let j = i +1; j < arr.length; j++) {
      if(arr[j] < arr[minIndex]) {
        minIndex = j
      }
    }
    if(minIndex !== 1) {
      [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)