开发者

Does anyone knows how to fix this Merge Sort?

http://pt.wikipedia.org/wiki/Merge_sort#Java That code does not compi开发者_JAVA百科le.

Thank you.


Here's a working implementation from http://rosettacode.org/wiki/Merge_sort#Java, linked to from the English Wikipedia article on merge sort.

import java.util.LinkedList;  
public class Merge<E extends Comparable<? super E>> {  
    public LinkedList<E> mergeSort(LinkedList<E> m){  
        if(m.size() <= 1) return m;  

        int middle= m.size() / 2;  
        LinkedList<E> left= new LinkedList<E>();  
        for(int i= 0;i < middle;i++) left.add(m.get(i));  
        LinkedList<E> right= new LinkedList<E>();  
        for(int i= middle;i < m.size();i++) right.add(m.get(i));  

        right= mergeSort(right);  
        left= mergeSort(left);  
        LinkedList<E> result= merge(left, right);  

        return result;  
    }  

    public LinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){  
        LinkedList<E> result= new LinkedList<E>();  

        while(!left.isEmpty() && !right.isEmpty()){  
            //change the direction of this comparison to change the direction of the sort  
            if(left.peek().compareTo(right.peek()) <= 0) result.add(left.remove());  
            else result.add(right.remove());  
        }  

        result.addAll(left);  
        result.addAll(right);  
        return result;  
    }  
}


There's a scope error using posicao in the call to System.arraycopy. Declaring that variable at the beginning of the mesclar method (rather than inside the for loop at the bottom) will get it to compile, but that won't necessarily mean the logic's good. Also, the nested if statements inside that for loop can't be used for assignment like that. Nested ternary operators would do the trick, but good luck having somebody else understand it. Instead, the assignment to vetor[inicio + posicao] should be duplicated inside each if block.


You have to wrap that inside a class definition and invoke it in a main method. Then it will both compile and run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜