You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
3.0 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. // The SortingAlgs class that implements insertion sort and iterative merge sort
  2. // your name here
  3. public class SortingAlgs {
  4. // card comparison
  5. public int compares(Card c1, Card c2) {
  6. if (c1.getSuit() < c2.getSuit())
  7. return -1;
  8. else if (c1.getSuit() > c2.getSuit())
  9. return 1;
  10. else {
  11. if (c1.getRank() > c2.getRank())
  12. return 1;
  13. else if (c1.getRank() < c2.getRank())
  14. return -1;
  15. else
  16. return 0;
  17. }
  18. }
  19. // insertion sort
  20. public void insertionSort(Card[] cardArray) {
  21. for (int start = 1; start < cardArray.length; start++) {
  22. int compare_to = start - 1;
  23. int current = start;
  24. while ((compare_to >= 0) && (compares(cardArray[compare_to], cardArray[current]) > 0)) {
  25. Card temp = cardArray[current];
  26. cardArray[current] = cardArray[compare_to];
  27. cardArray[compare_to] = temp;
  28. current = compare_to;
  29. compare_to--;
  30. }
  31. }
  32. }
  33. // merge sort
  34. public void mergeSort(Card[] cardArray) {
  35. for (int run_length = 1; run_length <= cardArray.length - 1; run_length *= 2) {
  36. int merged_size = run_length * 2;
  37. for (int first = 0; first < cardArray.length - 1; first += merged_size) {
  38. int mid = first + run_length - 1;
  39. if (mid > cardArray.length - 1)
  40. mid = cardArray.length - 1;
  41. int last;
  42. if (first + merged_size < cardArray.length) {
  43. last = first + merged_size - 1;
  44. }
  45. else
  46. last = cardArray.length - 1;
  47. merge(cardArray, first, mid, last);
  48. }
  49. }
  50. }
  51. // merge two sorted arrays into one sorted array
  52. public void merge(Card[] cardArray, int first, int mid, int last) {
  53. Card[] aux1 = new Card[mid - first + 1];
  54. Card[] aux2 = new Card[last - mid];
  55. for (int i = 0; i < aux1.length; i++)
  56. aux1[i] = cardArray[i + first];
  57. for (int i = 0; i < aux2.length; i++)
  58. aux2[i] = cardArray[i + mid + 1];
  59. int main_index = first;
  60. int l_index = 0;
  61. int r_index = 0;
  62. while ((l_index < aux1.length) && (r_index < aux2.length)) {
  63. if (compares(aux1[l_index], aux2[r_index]) <= 0) {
  64. cardArray[main_index] = aux1[l_index];
  65. l_index++;
  66. }
  67. else {
  68. cardArray[main_index] = aux2[r_index];
  69. r_index++;
  70. }
  71. main_index++;
  72. }
  73. for (l_index = l_index; l_index < aux1.length; l_index++) {
  74. cardArray[main_index] = aux1[l_index];
  75. main_index++;
  76. }
  77. for (r_index = r_index; r_index < aux2.length; r_index++) {
  78. cardArray[main_index] = aux2[r_index];
  79. main_index++;
  80. }
  81. }
  82. }