Created
September 12, 2013 18:18
-
-
Save AnimeshShaw/6541715 to your computer and use it in GitHub Desktop.
Selection Sort 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 SelectionSort { | |
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 SelectionSort(Comparable[] a) { | |
int n = a.length, min; | |
for (int i = 0; i < n; i++) { | |
min = i; | |
for (int j = i + 1; j < n; j++) { | |
if (checkMin(a[j], a[min])) { | |
min = j; | |
} | |
} | |
swap(a, i, min); | |
} | |
} | |
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 Selection Sort"); | |
b = a.trim().split(" "); | |
SelectionSort(b); | |
display(b); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment