gpt4 book ai didi

java - 合并排序不起作用

转载 作者:行者123 更新时间:2023-11-30 07:50:02 25 4
gpt4 key购买 nike

我有一个对象的 ArrayList,我试图按对象中存储的“保存”编号对其进行排序。到目前为止我的代码写在下面

public static void mergesort(ArrayList<Object> list){
if(list.size() > 1){
//Split the list in half and create an ArrayList for each side
int q = list.size()/2;
//System.out.println(list.size() + " " + q);
ArrayList<Object> leftList = new ArrayList<Object>();
for(int i = 0; i > q; i++){
leftList.add(list.get(i));
}
ArrayList<Object> rightList = new ArrayList<Object>();
for(int j = q; j < list.size(); j++){
rightList.add(list.get(j));
}
// System.out.println(" leftList " + leftList.size() + " rightList " + rightList.size());
//sort each half of the list
//note: this will happen recursively
mergesort(leftList);
mergesort(rightList);
merge(leftList, rightList, list);
}
}
public static void merge(ArrayList<Object> leftList, ArrayList<Object> rightList, ArrayList<Object> list){
//'i' stores the index of the main array
//'l' stores the index of the left array
//'r' stores the index of the right array
int i = 0, l = 0, r = 0;
//the loop will run until one of the arraylists becomes empty
while(leftList.size() != l && rightList.size() !=r){
//if the saving of the current element of leftList is less than the rightList saving
if(leftList.get(l).getSaving() < rightList.get(r).getSaving()){
//Copy the current element into the final array
list.set(i, leftList.get(l));
i++;
l++;
}
else {
list.set(i, rightList.get(r));
i++;
r++;
}
}

while(leftList.size() != l){
list.set(i, leftList.get(l));
i++;
l++;
}

while(rightList.size() != r){
list.set(i,rightList.get(r));
i++;
r++;
}


}

出于某种原因,当我运行它时,我没有收到任何错误,但是,列表仍然未排序。任何建议将不胜感激。提前致谢

最佳答案

问题出在归并排序方法的第一个 for 中:

for (int i = 0; i > q; i++) {

应该是:

for (int i = 0; i < q; i++) {

检查状况..

关于java - 合并排序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33421673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com