Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static ArrayList<Integer> merge_sort(ArrayList<Integer> arr) {
- // Write your code here.
- merge_sort_helper(arr, 0, arr.size()-1);
- return arr;
- }
- static void merge_sort_helper(ArrayList<Integer> arr, int start, int end) {
- ArrayList<Integer> auxList = new ArrayList<>();
- // Base Case
- if(start == end) {
- return;
- }
- // Recursive case
- int mid = start + (end - start) /2;
- merge_sort_helper(arr, start, mid);
- merge_sort_helper(arr, mid+1, end);
- // Merge sub-list
- int i=start;
- int j=mid+1;
- while(i<=mid && j<=end) {
- if(arr.get(i) <= arr.get(j)) {
- auxList.add(arr.get(i));
- i++;
- } else {
- auxList.add(arr.get(j));
- j++;
- }
- }
- while(i<=mid) {
- auxList.add(arr.get(i));
- i++;
- }
- while(j<=end) {
- auxList.add(arr.get(j));
- j++;
- }
- for(int idx = start; idx <= end; idx++) {
- arr.set(idx, auxList.get(idx - start));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement