/** This program is intended to be used with the book "Java 7 -- What Do You Want To Do?"
 * by Steven P. Warr and is distributed free of charge and without and expectations of remuneration.
 * Chapter ALG   NOTE all program names begin with title of the chapter in which
 * they are intended to be used.   Copyright 2010 Steven P. Warr All rights reserved
 */
//alg 06
import java.util.*; 
import java.io.*; 
public class Alg06 
{
   public static void main(String[ ] args) throws IOException
    {
    	Scanner infile = new Scanner(new File("alg05.data"));
		Scanner keyIn = new Scanner(System.in);
		int x = 0;
		int totalNumber = 0;
		totalNumber = infile.nextInt(); //First number in data file is the 
										//is the count.
		int [] number = new int[totalNumber];										
		System.out.println("Original array" + " " + totalNumber);
		while (infile.hasNext())
		     {
				number[x] = infile.nextInt();
				System.out.println(number[x]);
				x++;
			}	
		bubbleSort(number);
		System.out.println("\nSorted array of " + totalNumber+ "\n");
		for(x = 0; x< number.length; x++)
			System.out.println(number[x]);
		
		
     }		
public static void bubbleSort(int [] list)
  {
       int endList = list.length-1;// -1 so data outside the array (x + 1)
       boolean flag = true;         //is not sorted into the array.
       while (flag)   		//If flag == true a swap has been made
          {          	 	//If no swaps are made, flag == false and 
          	flag = false; 	//the loop ends early.
            for (int x = 0; x< endList; x++)
	            {
			 		if (list[x] > list[x+1]) //This is ascending.  Change < to
			 		    {					// > for descending order.
			                flag = true;   	// Make flag true when a swap is made.
			                swap(list,x,x+1);//Data is not sorted.
			            }    
		        }
		    endList --; //The end (top) of the list gets sorted first.  There is
		  }             //no need to check it again, thus data bubbles up.

 }	
public static void swap(int[] list, int x , int y)
{
	int temp = list [x];     //The same swap algorithm as in sequential sort 
	list[x] =list[y];     	 //and selection sort.
	list[y]= temp;      	
}
}
