Saturday, May 31, 2014

MergeSort with Comparable and Lists


Hello guys!


I have big problem with mergesort in Java. I can't figure out why it do not works.


I need write it on lists using Comparable. Here is piece of code:



Java Code:



class MergeSort{
Comparator _comparator;
List lista = new ArrayList<>();
List list_temp = new ArrayList<>();



MergeSort(Comparator comparator){
_comparator = comparator;
}
void sort(List lista){
this.lista = lista;

mergesort(0, lista.size()-1);

}

void mergesort(int start, int end){
if(start < end){
int mid = start + (end-start)/2;

mergesort(start, mid);
mergesort(mid+1, end);

merge (start, mid, end);
}


}

void merge(int start, int mid, int end){

int i = start;
int j = mid + 1;
int k = start;

for(int h = start; h <= end; h++)
list_temp.add(lista.get(h));

while (i <= mid && j <= end) {
if (_comparator.compare(list_temp.get(i),list_temp.get(j)) <= 0) {
lista.set(k, list_temp.get(i));
i++;
}
else{
lista.set(k, list_temp.get(j));
j++;
}
k++;

while (i <= mid) {
lista.set(k, list_temp.get(i));
k++;
i++;
}
}



}

final class NaturalComparator implements Comparator{
public static final NaturalComparator INSTANCE = new NaturalComparator();

NaturalComparator(){}

@Override
public int compare(Object left, Object right) throws ClassCastException{
return ((Comparable) left).compareTo(right);
}
}



I have tried everything, still no results. It's return list with random placed numbers.

Thnak you for any advice!



No comments:

Post a Comment