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.
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]
if (min_index !=i) then
swap li [min_value] and li [ i ]
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.
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
var temp = ar[min_index];
ar[min_index] = ar[i];
ar[i] = temp;
- How to write a resume for a job search: Tips for applicants - May 11, 2021
- The Best Tool to Test the Speed of Your Internet - May 5, 2021
- Why do we need various number systems in computer science? - April 16, 2021