Selection Sort

Description

Selection sort is a simple sorting algorithm, where the given list is divided into 2 parts, the sorted part and the unsorted part. Initially, the sorted part is empty and the unsorted part is the entire list. The smallest element is selected from the unsorted part and swapped with the leftmost element in the list, which becomes a element in the sorted part. This process continues until all the elements in the unsorted part is moved to the sorted part.

Code


  function selection(arr,n) 
  {
      for(let i=0; i < n-1; i++) {
          let min = arr[i];
          let index = i;
          for(let j=i ;j < n;j++) {
              comparisons++;
              if(arr[j] < min) {
                  min = arr[j];
                  index = j;
              }
          }
          swaps++;
          let temp = arr[i];
          arr[i] = arr[index];
          arr[index] = temp;
      }
      return arr;
  }
                    
Complexity
Time Complexity:

Best Case : Ω (n^2)
Average Case : θ (n^2)
Worst Case: O (n^2)

Space Complexity:

O(1)

** where n is the length of the array

To Learn more about Selection Sort, refer the link given below: Selection sort