Advertisement
Guest User

Untitled

a guest
Apr 16th, 2014
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. public void mergeSort(ArrayList <Comparable> a, int first, int last)
  2. {
  3. if((last-first)==1)
  4. {
  5. }
  6. else if((last-first)==2)
  7. {
  8. if((a.get(first).compareTo(a.get(last))>0))
  9. {
  10. a.add(first, a.remove(last));
  11. }
  12. }
  13. else
  14. {
  15. mergeSort(a, first, ((last+first)/2));
  16. mergeSort(a, ((last+first)/2+1), last);
  17. merge(a,first,((last+first)/2), last);
  18. }
  19. }
  20. // creates a copy of ArrayList list called temp, and uses temp’s values to properly merge(sort) list
  21. // from first to last
  22. public void merge(ArrayList<Comparable> list, int first, int mid, int last)
  23. {
  24. List<Comparable> copy = new ArrayList<Comparable>();
  25. for(int i = 0; i<list.size(); i++)
  26. {
  27. copy.add(list.get(i));
  28. }
  29. int index1=first;
  30. int index2=mid+1;
  31. for(int i = first; i<=last; i++)
  32. {
  33. if(index1>mid)
  34. {
  35. list.set(i, copy.get(index2));
  36. index2++;
  37. }
  38. else if(index2 >last)
  39. {
  40. list.set(i, copy.get(index1));
  41. index1++;
  42. }
  43. else if(copy.get(index1).compareTo(copy.get(index2))<0)
  44. {
  45. list.set(i, copy.get(index1));
  46. index1++;
  47. }
  48. else
  49. {
  50. list.set(i, copy.get(index2));
  51. index2++;
  52. }
  53. }
  54.  
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement