Site icon T4Tutorials.com

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:

Program of Selection Sort in Javascript

<html>
<body>
<script>
   var ar = [0,4,3,1,5,6,2];
   document.write("<br>");
   document.write("Unsorted Array <br><br>");
   document.write(ar);
   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("<br><br>");
   document.write("Sorted Array<br><br>")
   document.write(ar);
   
</script>
   
</body>
</html>

Output

Unsorted Array

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

Sorted Array

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

Exit mobile version