Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public void mergeSort(ArrayList <Comparable> a, int first, int last)
- {
- if((last-first)==1)
- {
- }
- else if((last-first)==2)
- {
- if((a.get(first).compareTo(a.get(last))>0))
- {
- a.add(first, a.remove(last));
- }
- }
- else
- {
- mergeSort(a, first, ((last+first)/2));
- mergeSort(a, ((last+first)/2+1), last);
- merge(a,first,((last+first)/2), last);
- }
- }
- // creates a copy of ArrayList list called temp, and uses temp’s values to properly merge(sort) list
- // from first to last
- public void merge(ArrayList<Comparable> list, int first, int mid, int last)
- {
- List<Comparable> copy = new ArrayList<Comparable>();
- for(int i = 0; i<list.size(); i++)
- {
- copy.add(list.get(i));
- }
- int index1=first;
- int index2=mid+1;
- for(int i = first; i<=last; i++)
- {
- if(index1>mid)
- {
- list.set(i, copy.get(index2));
- index2++;
- }
- else if(index2 >last)
- {
- list.set(i, copy.get(index1));
- index1++;
- }
- else if(copy.get(index1).compareTo(copy.get(index2))<0)
- {
- list.set(i, copy.get(index1));
- index1++;
- }
- else
- {
- list.set(i, copy.get(index2));
- index2++;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement