Guest User

Untitled

a guest
Dec 15th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. MYSORT
  2. /*
  3. * To change this template, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package collection;
  7.  
  8. /**
  9. *
  10. * @author James
  11. */
  12. public class MySort {
  13.  
  14. private MySort() {} // Prevents Instantiation
  15.  
  16. /*
  17. *
  18. */
  19. public static void swap(MyVector vec, int first, int second)
  20. {
  21. Object temp = vec.elementAt(first);
  22. vec.replace(first, vec.elementAt(second));
  23. vec.replace(second, temp);
  24. }
  25.  
  26. /*
  27. *
  28. */
  29.  
  30. public static MyVector bubbleSort(MyVector vec)
  31. {
  32. int i,
  33. j,
  34. n = vec.size();
  35. Comparable first,
  36. second;
  37. for (i = 1; i < n; i++)
  38. for (j = n - 1; j >= i; j--)
  39. {
  40. first = (Comparable)vec.elementAt(j-1);
  41. second = (Comparable)vec.elementAt(j);
  42. if (first.compareTo(second) > 0)
  43. swap(vec, j - 1, j);
  44. }
  45. return vec;
  46. }
  47.  
  48. /*
  49. *
  50. */
  51.  
  52. public static MyVector selectionSort(MyVector vec)
  53. {
  54. int i,j, n = vec.size();
  55. int smallPos;
  56. Comparable smallest, current;
  57. for (i = 0; i < n - 1; ++i)
  58. {
  59. smallPos = i;
  60. smallest = (Comparable)vec.elementAt(i);
  61. for (j = i + 1; j < n; ++j)
  62. {
  63. current = (Comparable)vec.elementAt(j);
  64. if (current.compareTo(smallest) < 0)
  65. {
  66. smallPos = j;
  67. smallest = current;
  68. }
  69. }
  70. swap(vec, i, smallPos);
  71. }
  72. return vec;
  73. }
  74. }
  75.  
  76. ------------- LAB CLASS
  77. public class Lab3 {
  78.  
  79. public static void test()
  80. {
  81.  
  82. MyVector numVec = new MyVector(61);
  83. Random r = new Random();
  84. r.setSeed(java.lang.System.nanoTime());
  85.  
  86. for (int i = 0; i < 61; i++)
  87. {
  88. if (i % 5 == 0) { System.out.print("\n"); }
  89. int data = new Integer(100 + r.nextInt(900));
  90. numVec.insertAt(i, data);
  91. System.out.print("Index:" + i + ": " + numVec.elementAt(i) + "\t");
  92. }
  93.  
  94. MySort.bubbleSort(numVec);
  95. for (int i = 0; i < 61; i++)
  96. {
  97. if (i % 5 == 0) { System.out.print("\n"); }
  98. System.out.print("Index:" + i + ": " + numVec.elementAt(i) + "\t");
  99. }
  100. }
  101. }
Add Comment
Please, Sign In to add comment