본문 바로가기

Javascript/Algorithms

Selection Sort

similar to bubble sort.

but instead of first placing large values into sorted position, the actual sorted data is accumulating at the beginning.

 

Selection Sort Pseudocode

  • Store the firtst element as the smallest vlaue you've seen so far.
  • Compare this item to the next item in the array until you find a smaller number
  • If a smaller number is found, designate that smaller number to be the new 'minimum' and continue until the end of the array.
  • If the 'minimum' is not the value (index) you initially began with, swap the two values.
  • Repeat this with the next element until the array is sorted.

It's a loop plus another loop and a single conditional and then at the end a swap.

 

function selectionSort(arr) {
    for(var i=0; i<arr.length; i++) {
        var lowest = i;
        for(var j=i+1; j<arr.length; j++){
            
            if(arr[j]<arr[lowest]){
                lowest = j;
            }        
        }
        var temp = arr[lowest];
        arr[lowest]= arr[i];
        arr[i] = temp;
    }
    return arr;
}

selectionSort([34,22,10,19,17]);

 

Big O Complexity

N^

selection sort is potentially is better than bubble sort.

you can minimize the number of swaps that you're making.

 

'Javascript > Algorithms' 카테고리의 다른 글

Merge Sort  (0) 2021.01.19
Insertion Sort  (0) 2021.01.03
Bubble Sort  (0) 2020.12.27
Searching Algorithms  (0) 2020.12.23
Recursion  (0) 2020.12.20