gpt4 book ai didi

java - 在 for 循环的条件语句中使用 vector.size() 时出现无限循环

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

我正在实现桶排序并使用插入排序对每个桶进行排序。但当我运行代码时,它进入了无限循环。经过调试,发现for循环无限运行。

// we have buckets for each intervals
// we add values into each bucket
// each bucket is then sorted at the end
// then all the buckets are merged together
public class BucketSort {


@SuppressWarnings("unchecked")
private Vector<Double>[] buckets = new Vector[10];


private int sizeOfInput;

//constructor

public BucketSort(int size){
sizeOfInput = size;
for(int i=0; i<10;i++){
buckets[i] = new Vector();

}

}


public static void main(String args[]){
Double[] arr = {0.11,0.12,0.21,0.61,0.7,0.5,0.14,0.2,0.61,0.65,0.72,0.80,0.98,0.82,0.96,0.35,0.47,0.53};

BucketSort s = new BucketSort(arr.length);

Vector result = s.bucketSort(arr);
System.out.println("The result is : ");

for(int i= 0;i< result.size();i++){
System.out.println(result.get(i));
}
//s.printBucket();
}

public void printBucket(){
// prints out the elements in each bucket
for(int i = 0; i<10;i++){
System.out.println("The bucket "+ i + " contains these elements");
for(int j=0; j<buckets[i].size();j++){

System.out.println(buckets[i].get(j));
}
}
}


public Vector bucketSort(Double[] arr){
// add the elements in appropriate buckets
for(int i = 0; i<arr.length;i++){
for(int j=0; j<10;j++){
if(arr[i] < (double)(j+1)/10){
buckets[j].add((double)arr[i]);
break;
}
}
}

// print out each bucket
printBucket();

// call the sort function on each of the buckets
for(int i= 0 ; i< 1; i++){

sort(1);
System.out.println("Sorted bucket" + i);
}


return merge();
}

public void sort(int number){

//binary sort each values of vector
System.out.println("bucket" + number + "size is " + buckets[number].size());
int k = buckets[number].size();

for(int i = 1; i < (buckets[number].size()); i++ ){
System.out.println("Bucket" + number + "element" + i);

double a = buckets[number].get(i);
int j= i;
while(j > 0 && buckets[number].get(j-1) > a){
//double b = buckets[no].get(j-1);
//buckets[no].add(j,b);
j--;
System.out.println("Sorting bucket" + number);
}

buckets[number].add(j,a);

}
}

public Vector merge(){
//merge all the bucket vectors into an array
Vector<Double> result = new Vector();

for(int j=0;j<10;j++){
//buckets[j].copyInto(result);
result.addAll(buckets[j]);
}

return result;
}

}

如果我更换

for(int i = 1; i < (buckets[number].size()); i++ ){

for(int i = 1; i < k; i++ ){

其中 k = 桶[数量].size()

这解决了问题,但我不明白为什么会出现错误。请解释这种不当行为的原因。

最佳答案

您正在循环内向存储桶添加内容,这会增加其大小。每次执行循环之前都会重新评估循环条件。

关于java - 在 for 循环的条件语句中使用 vector.size() 时出现无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28934028/

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