Advertisement
Psycho_Coder

Selection Sort implemented in Java

Oct 10th, 2014
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1.  
  2. import java.util.Scanner;
  3.  
  4. public class SelectionSort {
  5.  
  6. private static void swap(Comparable[] a, int i, int j) {
  7. Comparable t = a[i];
  8. a[i] = a[j];
  9. a[j] = t;
  10. }
  11.  
  12. private static boolean checkMin(Comparable v, Comparable w) {
  13. return v.compareTo(w) < 0;
  14. }
  15.  
  16. private static void display(Comparable[] a) {
  17. for (int i = 0; i < a.length; i++) {
  18. System.out.print(a[i] + "\t");
  19. }
  20. }
  21.  
  22. private static void SelectionSort(Comparable[] a) {
  23. int n = a.length, min;
  24. for (int i = 0; i < n; i++) {
  25. min = i;
  26. for (int j = i + 1; j < n; j++) {
  27. if (checkMin(a[j], a[min])) {
  28. min = j;
  29. }
  30. }
  31. swap(a, i, min);
  32. }
  33. }
  34.  
  35. public static void main(String[] args) {
  36. String a;String[] b;
  37. Scanner sc = new Scanner(System.in);
  38. System.out.println("Enter the data to be sorted seperated by space :-");
  39. a = sc.nextLine();
  40.  
  41. System.out.println("\nSort using Selection Sort");
  42.  
  43. b = a.trim().split(" ");
  44. SelectionSort(b);
  45. display(b);
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement