Programmatic Approach for Insertion Sort
- For sorting an array using insertion sort first iterate the array using for loop and always keep the current element in a temp varaible or key in this case.
- Now at every iteration compare the key value to all previouse element, in case key value is greater do nothing, but in case it is smallar swap back all predecessors till the value reaches at right position i.e. left one should be smallar and right one should be greater.
- Complete all iteration with along with above mentioned steps and return the final sorted array.
Example:
Javascript
// Function to implement insertion sort function selectionSort(arr) { // Getting the array length let n = arr.length; // To store value temporarily let key; // For iterations let i, j; // Iterate array in forward direction for (i = 0; i < n ; ++i) { key = arr[i]; j = i - 1; // Iterate and swap elements in backward direction // till number is greater then the key for (j; j >= 0, arr[j]>key; --j){ arr[j+1]=arr[j]; } // Swap the key to right position arr[j+1]=key; } } // Input array const arr = [64, 25, 12, 22, 11]; // Display Input array console.log( "Original array: " + arr); // Sort using function selectionSort(arr); // Display the output array after sorting console.log( "After sorting: " + arr); |
Output
Original array: 64,25,12,22,11 After sorting: 11,12,22,25,64