Selection Sort in Javascript

Selection Sort in Javascript

Algorithm of Selection Sort

Step 1 – take an unsorted array and make it sorted an array with the help of selection sort

Step 2 – then apply the selection sort algorithm on an array

Step 3 – in selection sort it will check all the array elements one by one when it will find the lowest value it will sort it in index “0”

Step 4 – again the loop will run until the sort arrange in ascending order.

Step 5 – Now we will have the sorted array.

Pseudo code of Selection Sort in Javascript

Start program

li= Array list

n= size of array

for (int i=0; i<n-1; i++)

min_value=i

for (int j=i+1; j < n; j++)

if ( li [ j ] < li [ min_value]

min_vale=j

end if

end for

if (min_index !=i) then

swap li [min_value] and li [ i ]

end if

end for

end program

The logic of Selection Sort in Javascript

Selection Sort in Javascript
Figure: Selection Sort in Javascript

Consider the following array as an example:

  • For the first position of the array, all the elements of the array are scanned one by one the first position where the 45 is placed then we search the whole array list and select the 41 the lowest no that is present in the array.
  • Then we swap the 45 with 41, after the 1st iteration the minimum valued of the unsorted array 41 is placed at the 1st position of the array.
    • Now we started the 2nd iteration, and again we scanned the whole array but now we have to place the 2nd lowest number at the 1st index of the array. So, now we select the 43 and scanned the whole array when we find the lowest no 42 than 43. then, we swap the 43 with 42. Now the 42 is at the 1st index of the array.
    • Now we have to do the 3rd iteration, in this iteration first we scan the whole array list here we found there is 43 at its own place. So, we check the next no and 45 is not at its place now we scanned the whole array and we find the 44 the lowest no than 45 then we swap the 45 with 44.
    • Now all the array elements of the array is sorted.

Program of Selection Sort in Javascript

Output

Unsorted Array

0,4,3,1,5,6,2

Sorted Array

0,1,2,3,4,5, 6

Latest posts by Prof. Fazal Rehman Shamil (see all)

Buy advertisement space on T4Tutorials

For more details email [email protected]