Site icon

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++)


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

if ( li [ j ] < li [ min_value]


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

Figure: Selection Sort in Javascript

Consider the following array as an example:

Program of Selection Sort in Javascript

   var ar = [0,4,3,1,5,6,2];
   document.write("Unsorted Array <br><br>");
   var i, j, min_index; 
   var m = ar.length; 
       // One by one read the all elements of the unsorted array 
       for ( i = 0; i < m-1; i++) 
           //here we  Find the minimum value in unsorted array 
           var min_index = i; 
           for ( j = i+1; j < m; j++) 
               if (ar[j] < ar[min_index) 
                   min_index = j; 
           // now Swap the found minimum value with the first index of the array 
           // element 
           var temp = ar[min_index]; 
           ar[min_index] = ar[i]; 
           ar[i] = temp; 
   document.write("Sorted Array<br><br>")


Unsorted Array


Sorted Array

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

Exit mobile version