// purpose: demonstrate sorting an array import java.util.*; public class ArraySort { public static void main( String[] args ) { // get a scanner for standard input Scanner stdin = new Scanner( System.in ); // determine the desired array size System.out.println(); System.out.print( "Enter number of elements: " ); int n = stdin.nextInt(); System.out.println(); // create the array int[] list = new int[ n ]; // put random integers between 0 .. 9 into the elements Random die = new Random(); for ( int i = 0; i < list.length; ++i ) { list[i] = die.nextInt( 10 ); } // display the array System.out.print( "list = " ); for ( int i = 0; i < list.length; ++i ) { System.out.print( list[ i ] + " " ); } System.out.println(); System.out.println(); // arrange the list -- repeatedly find the smallest unarranged // element and place it right after the already arranged elements for ( int i = 0; i < list.length; ++i ) { // find the smallest unarranged value and place it in the ith spot // set k to be the index of the smallest unarranged value. guess // its i and then check the other elements to see if the guess // needs updating int k = i; for (int j = i+1; j < list.length; ++j ) { if ( list[ j ] < list[ k ] ) { // update guess for k k = j; } } // list[ k ] is the smallest unarranged value, swap it with // list[ i ] int rmbr = list[ i ]; list[ i ] = list[ k ]; list[ k ] = rmbr; } // redisplay the array System.out.print( "list = " ); for ( int i = 0; i < list.length; ++i ) { System.out.print( list[ i ] + " " ); } System.out.println(); System.out.println(); } }