Implementation of Selection Sort

Implementation of Selection Sort

  • Selection Sort is one of the easier sorting algorithms to understand and implement.

  • This algorithm splits the array into two parts:

    1. Sorted

    2. Unsorted

  • The Sorted part is at the beginning of the array and the Unsorted part afterward.

  • For each pass, initially, we assume the first element to be the smallest then we loop through the whole array and select the smallest element. At the end of the pass, we swap the smallest element to the sorted array.

  • It has O(n2) time complexity.

function selectionSort(array) {
  // Only change code below this line
  let i, j, min,temp;
  let n = array.length
  for(i=0;i<n-1;i++){
    min = i;
    for(j=i+1; j<n; j++){
      if(array[min] > array[j]){
           min = j;
      }
      temp = array[i];
      array[i] = array[min];
      array[min] =temp;
    }
  }
  return array;
  // Only change code above this line
}