我不明白这段代码中发生了什么。从之前重新发布包含的代码。有人可以解释一下这里发生了什么吗?我从概念上理解列表是一次重新排序一个项目,但我不能理解这个代码。
import java.io*;
public class Example {
public static void main(String[] args) throws IOException {
int age[] = new int[10];
int i, j;
int smallest;
int temp;
String line;
BufferedReader in;
in = new BUfferedReader(new InputStreamReader(System.in));
for(i = 0; i<= 9; i++)
{
System.out.println("Enter an age: ");
line = in.readline();
age[i] = Integer.valueOf(line).intValue();
}
for(i = 0; i<= 9, i++) {
smallest = i;
for(j = 1; j<=9; j++)
{
if(age[j] < age[smallest]) {
smallest = j;
}
}
for (i = 0; i<=9; i++)
{
System.out.println(age[i]);
}
}
}
}
答案 0 :(得分:2)
这看起来像 Bubble Sort 的实现。关于这个经典(和低效!)算法的主题,在互联网和基础算法主题的书籍中都有大量的信息。
答案 1 :(得分:0)
import java.io *;
公共类示例{
public static void main(String [] args)抛出IOException {
int age[] = new int[10];
int i, j;
int smallest;
int temp;
String line;
BufferedReader in;
in = new BUfferedReader(new InputStreamReader(System.in));
for(i = 0; i<= 9; i++)
{
System.out.println("Enter an age: ");
line = in.readline();
age[i] = Integer.valueOf(line).intValue();
}
for(i = 0; i<= 9, i++) {
smallest = i;
for(j = 1; j<=9; j++)// MISTAKE IS IN THIS LINE; YOU SHOULD START THE VALUE OF J FROM I+1(for(j = i+1; j<=9; j++)))
{
if(age[j] < age[smallest]) {
smallest = j;
}
}
//ALSO AFTER FINDING THE SMALLEST ELEMENT YOU HAVE TO SWAP THE SMALLEST ELEMENT WITH I ELEMENT
/*int temp=age[i];
age[i]=age[smallest];
age[smallest]=temp*/
for (i = 0; i<=9; i++)
{
System.out.println(age[i]);
}
}
}
}