Created
September 12, 2013 18:23
-
-
Save AnimeshShaw/6541791 to your computer and use it in GitHub Desktop.
InsertionSort implemented in Java
This file contains 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
import java.util.Scanner; | |
public class InsertionSort { | |
private static void swap(Comparable[] a, int i, int j) { | |
Comparable t = a[i]; | |
a[i] = a[j]; | |
a[j] = t; | |
} | |
private static boolean checkMin(Comparable v, Comparable w) { | |
return v.compareTo(w) < 0; | |
} | |
private static void display(Comparable[] a) { | |
for (int i = 0; i < a.length; i++) { | |
System.out.print(a[i] + "\t"); | |
} | |
} | |
private static void InsertionSort(Comparable[] a) { | |
int n=a.length,j; | |
Comparable key; | |
for (int i=1;i<n;i++){ | |
key=a[i]; | |
j=i; | |
while(j>0 && checkMin(key, a[j-1])){ | |
a[j] = a[j-1]; | |
j = j-1; | |
} | |
a[j] = key; | |
} | |
} | |
public static void main(String[] args) { | |
String a;String[] b; | |
Scanner sc = new Scanner(System.in); | |
System.out.println("Enter the data to be sorted seperated by space :-"); | |
a = sc.nextLine(); | |
System.out.println("\nSort using Insertion Sort"); | |
b = a.trim().split(" "); | |
InsertionSort(b); | |
display(b); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment