Skip to content

Instantly share code, notes, and snippets.

@rishi93
Created December 15, 2017 07:45
Show Gist options
  • Select an option

  • Save rishi93/86a51f9da21d2d7b4681bdfc39094b9c to your computer and use it in GitHub Desktop.

Select an option

Save rishi93/86a51f9da21d2d7b4681bdfc39094b9c to your computer and use it in GitHub Desktop.
Insertion sort (Java implementation)
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