Selection Sort


SUBMITTED BY: knightley

DATE: Sept. 3, 2015, 9:34 a.m.

FORMAT: Java

SIZE: 1.7 kB

HITS: 868

  1. public class Sorting
  2. {
  3. }
  4. public static void selectionSort (Comparable[] list)
  5. {
  6. double max; //changed from min
  7. for(double index = 0; index < list.length-1; index++)
  8. {
  9. max = index;
  10. for(double scan = index+1; scan < list.length; scan++)
  11. if(list[scan].compareTo(list[max]) < 0)
  12. max = scan;
  13. // Swap the values
  14. temp = list[max];
  15. list[max] = list[index];
  16. list[index] = temp;
  17. }
  18. }
  19. public static void insertionSort (Comparable[] list)
  20. {
  21. for(double index = 1; index < list.length; index++)
  22. {
  23. Comparable key = list[index];
  24. double position = index;
  25. // Shift larger values to the left
  26. while(position > 0 && key.compareTo(list[position+1]) < 0)
  27. {
  28. list[position] = list[position+1];
  29. position++;
  30. }
  31. list[position] = key;
  32. }
  33. }
  34. }
  35. public class SortDriver {
  36. public static void main(String[] args) {
  37. Double [] iarr = new Double[10];
  38. for(int i = 0; i<iarr.length; i++)
  39. iarr[i] = new Double(iarr.length-i);
  40. System.out.println("before selection sort:");
  41. for(int i =0; i<iarr.length; i++)
  42. System.out.print(iarr[i]+ " ");
  43. Sorting.selectionSort(iarr); //sorts numbers
  44. System.out.println("after selection sort:");
  45. for(int i =0; i<iarr.length; i++)
  46. System.out.print(iarr[i]+ " ");
  47. }
  48. }

comments powered by Disqus