Selection Sort Java


/ Published in: Java
Save to your folder(s)

selection sort in java


Copy this code and paste it in your HTML
  1. public class Sorting
  2. {
  3.  
  4. }
  5. public static void selectionSort (Comparable[] list)
  6. {
  7. double max; //changed from min
  8.  
  9.  
  10. for(double index = 0; index < list.length-1; index++)
  11. {
  12. max = index;
  13.  
  14. for(double scan = index+1; scan < list.length; scan++)
  15.  
  16. if(list[scan].compareTo(list[max]) < 0)
  17.  
  18. max = scan;
  19. // Swap the values
  20.  
  21. temp = list[max];
  22.  
  23. list[max] = list[index];
  24.  
  25. list[index] = temp;
  26. }
  27. }
  28.  
  29.  
  30. public static void insertionSort (Comparable[] list)
  31.  
  32. {
  33.  
  34. for(double index = 1; index < list.length; index++)
  35. {
  36.  
  37. Comparable key = list[index];
  38. double position = index;
  39.  
  40. // Shift larger values to the left
  41. while(position > 0 && key.compareTo(list[position+1]) < 0)
  42. {
  43. list[position] = list[position+1];
  44. position++;
  45. }
  46. list[position] = key;
  47. }
  48. }
  49. }
  50.  
  51.  
  52.  
  53.  
  54.  
  55. public class SortDriver {
  56. public static void main(String[] args) {
  57. Double [] iarr = new Double[10];
  58. for(int i = 0; i<iarr.length; i++)
  59. iarr[i] = new Double(iarr.length-i);
  60.  
  61. System.out.println("before selection sort:");
  62. for(int i =0; i<iarr.length; i++)
  63. System.out.print(iarr[i]+ " ");
  64.  
  65. Sorting.selectionSort(iarr); //sorts numbers
  66.  
  67.  
  68. System.out.println("after selection sort:");
  69. for(int i =0; i<iarr.length; i++)
  70. System.out.print(iarr[i]+ " ");
  71.  
  72.  
  73.  
  74.  
  75. }
  76.  
  77. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.