Created
May 25, 2019 03:36
-
-
Save sanjulamadurapperuma/25677635f216b9fa858d8051140e47f2 to your computer and use it in GitHub Desktop.
Insertion Sort Java Implementation for Medium Article - @sanjulamadurapperuma
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
| package com.sanjula.java.algorithms.InsertionSort; | |
| public class InsertionSort { | |
| /** | |
| * Sort method using insertion sort | |
| * @param arr - Integer array passed in | |
| * to be sorted | |
| **/ | |
| public void sort(int arr[]){ | |
| // Store the length of the array | |
| int n = arr.length; | |
| // For loop to iterate through each | |
| for (int i = 0; i < n; i++){ | |
| // Storing current element to check correct position | |
| int key = arr[i]; | |
| int j = i - 1; | |
| // Move element to correct position if | |
| // condition is true | |
| while(j >= 0 && arr[j] > key){ | |
| arr[j + 1] = arr[j]; | |
| j = j - 1; | |
| } | |
| arr[j + 1] = key; | |
| } | |
| } | |
| /** | |
| * Print the array supplied | |
| * @param arr - Array passed | |
| * @param msg - Message to be printed | |
| **/ | |
| public static void printArray(int arr[], String msg) { | |
| int length = arr.length; | |
| System.out.println(msg); | |
| for (int i = 0; i < length; i++) { | |
| System.out.print(arr[i] + " "); | |
| } | |
| System.out.println(); | |
| } | |
| public static void main(String[] args) { | |
| // Initialize and declare the array arr | |
| int arr[] = {25, 12, 3, 1, 9, 15}; | |
| // Create new instance of class InsertionSort | |
| InsertionSort insertionSort = new InsertionSort(); | |
| printArray(arr, "Array before insertion sort"); | |
| // Invoke the sort method, passing in the array arr | |
| insertionSort.sort(arr); | |
| // Print the sorted array | |
| printArray(arr, "Array after insertion sort"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment