将hashmap作为输入的arraylist的mergesort

mgdq6dx1  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(188)

所以我有一个arraylist,它以hashmap作为输入。我想执行mergesort,但不知道如何实现它。我创建了两个helper方法,但是我不知道main方法应该返回什么(我必须使用main方法)
将哈希Map作为输入的主方法:

  1. public static <K, V extends Comparable> ArrayList<K> mergeSort (HashMap<K, V> results) {
  2. }
  1. private <K extends Comparable> ArrayList<K> mergeSortHelper(ArrayList<K> all) {
  2. ArrayList<K> firstPart = new ArrayList<K>();
  3. ArrayList<K> secondPart = new ArrayList<K>();
  4. int middle;
  5. if(all.size()==1) {
  6. return all;
  7. }
  8. else {
  9. middle = all.size()/2;
  10. //the first half
  11. for(int i = 0; i<middle;i++) {
  12. firstPart.add(all.get(i));
  13. }
  14. //the second half
  15. for(int i = middle; i<all.size();i++) {
  16. secondPart.add(all.get(i));
  17. }
  18. firstPart = mergeSortHelper(firstPart);
  19. secondPart = mergeSortHelper(secondPart);
  20. }
  21. return all;
  22. }
  23. private <K extends Comparable> void merge(ArrayList<K> firstPart,ArrayList<K>secondPart , ArrayList<K> all) {
  24. int leftIndex = 0;
  25. int rightIndex = 0;
  26. int allIndex = 0;
  27. //taking the smallest of the first and second part and adding them up
  28. while(leftIndex< firstPart.size() && rightIndex < secondPart.size()) {
  29. if((firstPart.get(leftIndex).compareTo(secondPart.get(rightIndex)))<0) {
  30. all.set(allIndex, firstPart.get(leftIndex));
  31. leftIndex++;
  32. }
  33. else {
  34. all.set(allIndex, secondPart.get(rightIndex));
  35. rightIndex++;
  36. }
  37. allIndex++;
  38. }
  39. //adding all the rest that is left
  40. ArrayList<K> restOfArray = new ArrayList<K>();
  41. int restOfIndex;
  42. if(firstPart.size() <= leftIndex) {
  43. restOfArray = secondPart;
  44. restOfIndex = rightIndex;
  45. }
  46. else {
  47. restOfArray = firstPart;
  48. restOfIndex = leftIndex;
  49. }
  50. for(int i = restOfIndex; i<restOfArray.size();i++) {
  51. all.set(allIndex, restOfArray.get(i));
  52. allIndex++;
  53. }
  54. }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题