我无法尝试从文件中加载50个元素到数组并调用冒泡排序。有人能告诉我我做错了什么。我已经将整个列表加载到数组中。只需要从中挑出50个第一个或随机元素并调用bubbleSort方法。
public class Sorts
{
public static int bubbleCount = 0;
public static void bubbleSort(double data[], int count)
{
int pass, i;
double temp;
boolean done;
done = false;
for (pass = 0; !done; pass++)
{
done = true;
for (i = 0; i < count - 1 - pass; i++)
{
bubbleCount++;
if (data[i] > data[i+1])
{
temp = data[i];
data[i] = data[i+1];
data[i+1] = temp;
done = false;
}
}
}
}
}
这是我的主要课程
public class MainSort
{
static File numData;
static Scanner s;
public static void main(String[] args) throws FileNotFoundException
{
numData = new File("Num.dat");
try
{
s = new Scanner(numData);
} catch (FileNotFoundException e) {
}
double[] array = new double[1];
while(s.hasNext())
{
int i=0;
array[i]=s.nextDouble();
//print
//System.out.println(array[i]);
i++;
}
Sorts sorted = new Sorts();
sorted.bubbleSort(array[50]);
}
}
答案 0 :(得分:0)
在循环外声明变量int i
:
int i=0;
while(s.hasNext()){
array[i]=s.nextDouble();
//print
//System.out.println(array[i]);
i++;
}
答案 1 :(得分:0)
问题在于这段代码
int i=0;
array[i]=s.nextDouble();
你在循环中声明了int i = 0;
var。每次设置为0。
因此,在数组中,每次索引0处的值都将替换为新值。
在int i
循环之外声明while
。
int i = 0;
while(s.hasNext()) {
array[i]=s.nextDouble();
i++;
}