将hashmap作为输入的arraylist的mergesort

mgdq6dx1  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(186)

所以我有一个arraylist,它以hashmap作为输入。我想执行mergesort,但不知道如何实现它。我创建了两个helper方法,但是我不知道main方法应该返回什么(我必须使用main方法)
将哈希Map作为输入的主方法:

public static <K, V extends Comparable> ArrayList<K> mergeSort (HashMap<K, V> results) {      
    }
private <K extends Comparable> ArrayList<K> mergeSortHelper(ArrayList<K> all) {
        ArrayList<K> firstPart = new ArrayList<K>();
        ArrayList<K> secondPart = new ArrayList<K>();
        int middle;

        if(all.size()==1) {
            return all;
        }
        else {
            middle = all.size()/2;
            //the first half
            for(int i = 0; i<middle;i++) {
                firstPart.add(all.get(i));
            }
            //the second half
            for(int i = middle; i<all.size();i++) {
                secondPart.add(all.get(i));
        }
            firstPart = mergeSortHelper(firstPart);
            secondPart = mergeSortHelper(secondPart);
        }
        return all;     
    }
        private <K extends Comparable> void  merge(ArrayList<K> firstPart,ArrayList<K>secondPart , ArrayList<K> all) {
            int leftIndex = 0;
            int rightIndex = 0;
            int allIndex = 0;
            //taking the smallest of the first and second part and adding them up
            while(leftIndex< firstPart.size() && rightIndex < secondPart.size()) {
                if((firstPart.get(leftIndex).compareTo(secondPart.get(rightIndex)))<0) {
                    all.set(allIndex, firstPart.get(leftIndex));
                    leftIndex++;
                }
                else {
                    all.set(allIndex, secondPart.get(rightIndex));
                    rightIndex++;
                }
                allIndex++;
            }
            //adding all the rest that is left 
            ArrayList<K> restOfArray = new ArrayList<K>();
            int restOfIndex;
            if(firstPart.size() <= leftIndex) {
                restOfArray = secondPart;
                restOfIndex = rightIndex;
            }
            else {
                restOfArray = firstPart;
                restOfIndex = leftIndex;
            }
            for(int i = restOfIndex; i<restOfArray.size();i++) {
                all.set(allIndex, restOfArray.get(i));
                allIndex++;
            }
        }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题