Java 合并两个列表
嗨 在像mergesort这样的代码中合并两个列表时,我确实有问题 这是我的代码,它将抛出一个异常,但我不知道为什么!请帮帮我Java 合并两个列表,java,exception,Java,Exception,嗨 在像mergesort这样的代码中合并两个列表时,我确实有问题 这是我的代码,它将抛出一个异常,但我不知道为什么!请帮帮我 private void solve(List<Point> upperHull) { list = upperHull; number = upperHull.size(); dcHullForUpperHull(0, number-1 ); } private void dcHullForUpperHull(int low, i
private void solve(List<Point> upperHull) {
list = upperHull;
number = upperHull.size();
dcHullForUpperHull(0, number-1 );
}
private void dcHullForUpperHull(int low, int high) {
/*System.out.println(list);*/
if (low<high) {
// Get the index of the Object which is in the middle
int mid = (low + high) / 2;
// Sort the left side of the list
dcHullForUpperHull(low, mid);
// Sort the Right side of the list
dcHullForUpperHull(mid +1 , high);
//combine them both.
mergeForUpperHull(low, mid, high);
}
}
private void mergeForUpperHull(int low, int mid, int high) {
List<Point> auxiliaryList = new ArrayList<Point>();
List<Point> auxiliaryListTow = new ArrayList<Point>();
for (int i = low; i <= mid; i++) {
auxiliaryList.add(upperHull.get(i));
}
for (int i = mid + 1; i <= high; i++) {
auxiliaryListTow.add(upperHull.get(i));
}
System.out.println(auxiliaryList.get(mid));
System.out.println(auxiliaryList.get(low));
}
for(int i=mid+1;i如果我没有弄错,如果列表的大小是3个或更多元素,那么
private void mergeForUpperHull(int low, int mid, int high)
方法将在某个时候被调用,其中低和中参数都具有相同的值,大于0。这肯定会导致您在尝试执行此操作时遇到异常
System.out.println(辅助列表.get(mid));
尝试逐行调试代码,这可能会对您有所帮助。
不过我只是个古玩,你为什么要这么做?你的代码摘录留下了很多猜测,老实说,它没有多大意义(至少对我来说没有)新的辅助列表中只有一个元素,它与您试图从系统输出中的辅助列表中获取的中间索引不对应
代码还有其他问题,但我假设您只是处于草稿行模式。但为了给您一些有效的指导,我不会在合并方法中使用两个辅助列表,而是使用主列表执行比较和交换操作。请记住,如果您只是为每个合并操作添加一个辅助列表,由于递归dcHullForUpperHull调用冒泡,最终列表中会有更多数据
更准确地说,您将从正在执行的合并中得到(Log2(列表大小)+1)*(列表大小)
元素(假设您每次都不创建全新的列表)
分治算法是很好的学习练习,因此我不会在这里给出完整的代码,但上面的内容应该是完成上述合并排序的正确方向是的,我已经用这种方式解决了问题删除“=”对于MID,您能否更新上述解决方案是如何解决问题的?我希望看到一个有效的解决方案?
for (int i = mid + 1; i <= high; i++) {
auxiliaryListTow.add(upperHull.get(i));
}
private void mergeForUpperHull(int low, int mid, int high)