MergeSort

Merge.gif
package algorithm.sort;

import java.util.ArrayList;
import java.util.List;

public class MergeSort {


    /**
     * Sorts the given List in place
     * @param listToSort the List to sort. Throws an error if its null
     */
    public void sort(List<Integer> listToSort) {
        if (listToSort == null) {
            throw new IllegalArgumentException("List is empty!");
        }
        if (listToSort.size() < 2) {
            return;
        }

        int mid = listToSort.size() / 2;
        List<Integer> left = new ArrayList<>(listToSort.subList(0, mid));
        List<Integer> right = new ArrayList<>(listToSort.subList(mid, listToSort.size()));

        sort(left);
        sort(right);
        mergeLists(left, right, listToSort);
        System.out.println(listToSort);
    }

    private void mergeLists(List<Integer> left, List<Integer> right, List<Integer> listToSort) {
        int leftIndex = 0;
        int rightIndex = 0;
        int listToSortIndex = 0;

        while (leftIndex < left.size() && rightIndex < right.size()) {
            if (left.get(leftIndex) < right.get(rightIndex)) {
                listToSort.set(listToSortIndex++, left.get(leftIndex++));
            } else {
                listToSort.set(listToSortIndex++, right.get(rightIndex++));
            }
        }
        while (leftIndex < left.size()) {
            listToSort.set(listToSortIndex++, left.get(leftIndex++));
        }
        while (rightIndex < right.size()) {
            listToSort.set(listToSortIndex++, right.get(rightIndex++));
        }
    }

}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容