gpt4 book ai didi

java - 使用归并排序对数组列表进行排序

转载 作者:行者123 更新时间:2023-12-01 15:21:39 25 4
gpt4 key购买 nike

我在将排序类转换为使用数组列表对对象进行排序时遇到问题。它当前正在对对象进行排序,但我在将其转换为对数组列表进行排序时遇到问题。这是代码:

package Merge_Sort_Objects_ArrayList;
import java.util.ArrayList;
public class mergesort {

/**
* Merges two sorted portion of items array
* pre: items[start.mid] is sorted. items[mid+1.end] sorted. start <= mid <= end
* post: items[start.end] is sorted
*/

private static void merge(ArrayList <Comparable> items, int start, int mid, int end){
Comparable temp;
int pos1 = start;
int pos2 = mid + 1;
int spot = start;
ArrayList <Comparable> objectSort = items;

while (!(pos1 > mid && pos2 > end)){
if ((pos1 > mid) || ((pos2 <= end) &&(items[pos2].getRadius() < items[pos1].getRadius()))){
temp[spot] = items[pos2];
pos2 +=1;
}else{
temp[spot] = items[pos1];
pos1 += 1;
}
spot += 1;
}
/* copy values from temp back to items */

for (int i = start; i <= end; i++){
items[i] = temp[i];
}
}

/**
* mergesort items[start..end]
* pre: start > 0, end > 0
* post: items[start..end] is sorted low to high
*/
public static void mergesort(ArrayList <Comparable> items, int start, int end){
if (start < end){
int mid = (start + end) / 2;
mergesort(items, start, mid);
mergesort(items, mid + 1, end);
merge(items, start, mid, end);
}
}
}

现在我已经开始转换它,但是我被困在这一部分:

  while (!(pos1 > mid && pos2 > end)){
if ((pos1 > mid) || ((pos2 <= end) &&(items[pos2].getRadius() < items[pos1].getRadius()))){
temp[spot] = items[pos2];
pos2 +=1;
}else{
temp[spot] = items[pos1];
pos1 += 1;
}
spot += 1;
}
/* copy values from temp back to items */

for (int i = start; i <= end; i++){
items[i] = temp[i];
}

提前谢谢您!

最佳答案

使用这样的事实

Foo[] array = ......;
Foo rhs = .....;
Foo lhs;
array[i] = rhs;
lhs = array[j];

类似于:

ArrayList<Foo> list = .....;
Foo rhs = ......;
Foo lhs;
list.set(i, rhs);
lhs = list.get(i);

关于java - 使用归并排序对数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10827051/

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