Search code examples
javaarrayssortingselection-sort

Java Selection Sort Confusion


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]);
           }
        }
    }
  }

Solution

  • 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.