Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private <T> void mergeSort(List<T> list, Comparator<T> comparator) {
- int divider = (list.size()) / 2;
- mergeSort(list, comparator, 0, divider - 1, divider, list.size() - 1);
- }
- private <T> void mergeSort(List<T> list, Comparator<T> comparator, int from0, int to0, int from1, int to1) {
- final int aFrom0 = from0;
- final int aSize0 = to0 - from0 + 1;
- final int aSize1 = to1 - from1 + 1;
- if (to0 - from0 >= 1) {
- int divider = from0 + (to0 - from0) / 2;
- mergeSort(list, comparator, from0, divider, divider + 1, to0);
- }
- if (to1 - from0 >= 1) {
- int divider = from1 + (to1 - from1) / 2;
- mergeSort(list, comparator, from1, divider, divider + 1, to1);
- }
- //We now have the elements divided up and at this point we definitely have only sorted elements in [from] to [to]
- //We have to repeat this step as often as we have elements in first AND second list
- while ((to0 - from0) >= 0 && (to1 - from1) >= 0) {
- T first0 = list.get(from0);
- T first1 = list.get(from1);
- int c = comparator.compare(first0, first1);
- if (c <= 0) {
- //Left is smaller than right, so we can put left first and remove it
- //if the first left is the first we add, we can leave it at its place in the list and just increment from0 by one (shifting)
- from0++;
- } else {
- //Left is bigger than right, so we can put the right first and remove it
- //this time we have to remove the element from the list and add it
- list.remove(from1);
- list.add(from0, first1);
- //Since we shifted the list we have to do some operations there
- from0++;
- to0++;
- from1++;
- }
- }
- //Check if we still have elements in list0, if yes add them to the end of the merged list
- int currentListEnd = aFrom0 + aSize1 + (aSize0 - (to0 - from0) - 1);
- while (to0 - from0 >= 0) {
- //Since to1 - from1 MUST be 0 now, we can see where we have to add them
- T toAdd = list.get(from0);
- list.remove(from0);
- list.add(currentListEnd, toAdd);
- //Now we have to shift list0 to the right by one while also decrementing it by one
- from0++;
- currentListEnd++;
- }
- //Check if we still have elements in list1, if yes add them to the end of the merged list
- currentListEnd = aFrom0 + aSize0 + (aSize1 - (to1 - from1));
- while (to0 - from0 >= 0) {
- //Since to0 - from0 MUST be 0 now, we can see where we have to add them
- T toAdd = list.get(from1);
- list.remove(from1);
- list.add(currentListEnd, toAdd);
- //Now we have to shift list1 to the right by one while also decrementing it by one
- from1++;
- currentListEnd++;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement