var numbers = new Array();
var tempnumbers = new Array();
var counter = 0;

function init()
{

  output='';
  bubblediv=document.getElementById('bubble');

	counter = 0;

	for( i=0; i<20; i++ )
	{

	  numbers[i]=Math.round( Math.random()*101 );

	}

	  output='';
	
	  for( j=0;j<(numbers.length-1);j++)
	  {
	  
	    output+=numbers[j]+"<br />"
	  
	  }
	  
	  bubblediv.innerHTML=output;  

	
}
	
function run()
{

	numbers=bubbleSort( numbers );

}
	
function bubbleSort( arrayToSort )
{

  counter++;

  document.getElementById('count').innerHTML="Loops through the array:"+counter;
  
  output='';
  bubblediv=document.getElementById('bubble');

    done=false;
 
    // loop through the array
    for( i=0;i<(arrayToSort.length-1);i++)
	{
	  
	  // if the O(n) > O(n+1) move O(n) to O(n+1) and O(n+1) to O(n)
	  if ( arrayToSort[i] > arrayToSort[i+1] )
	  {
	  
	    current=arrayToSort[i+1];	  
	  
	    arrayToSort[i+1]=arrayToSort[i];
		arrayToSort[i]=current;
	  
	    done=true;
	  
	  }
	
	}
  
    tempnumbers=arrayToSort;
  
	  output='';
	
	  for( j=0;j<(arrayToSort.length-1);j++)
	  {
	  
	    output+=arrayToSort[j]+"<br />"
	  
	  }
	  
	  bubblediv.innerHTML=output;  
  
      if ( done==true )
	  {
	  
	   setTimeout( "bubbleSort(tempnumbers)",250 );
	  
	  }
  
  return arrayToSort;
  
}
