Reputation: 671
I don't understand what is happening in this code. Re-post from before with code included. Can someone please explain what is happening here? I understand conceptually that the list is being re-ordered one item at a time, but I just cant grasp this code.
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]);
}
}
}
}
Upvotes: 0
Views: 84
Reputation: 1
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++)// 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]);
}
}
}
}
Upvotes: 0
Reputation: 1593
This looks like an implementation of the Bubble Sort. There is a wide wealth of information on the topic of this classic (and inefficient!) algorithm both on The Internet and in books on the subject of fundamental algorithms.
Upvotes: 2