Created
December 15, 2017 07:45
-
-
Save rishi93/86a51f9da21d2d7b4681bdfc39094b9c to your computer and use it in GitHub Desktop.
Insertion sort (Java implementation)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class InsertionSort{ | |
| public void insertionsort(int[] arr, int n){ | |
| int j, key; | |
| for(int i = 1; i < n; i++){ | |
| key = arr[i]; | |
| j = i-1; | |
| while(j >= 0 && key < arr[j]){ | |
| arr[j+1] = arr[j]; | |
| j -= 1; | |
| } | |
| arr[j+1] = key; | |
| } | |
| } | |
| } | |
| public class Test{ | |
| public static void main(String[] args){ | |
| InsertionSort ob = new InsertionSort(); | |
| int[] arr = {5, 3, 2, 4, 1}; | |
| int n = arr.length; | |
| ob.insertionsort(arr, n); | |
| System.out.println("After sorting"); | |
| for(int i = 0; i < n; i++){ | |
| System.out.print(arr[i] + " "); | |
| } | |
| System.out.println(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment