Running jsdemo2.js

➕︎ Aa ➖︎ |Dark 1Dark 2Light|HackFira Code|Back to  PT Mono
// CPCS 223 Analysis & Design of Algorithms
// Javascript demo 2 - functions and local variables
// 2020, Dr. Muhammad Al-Hashimi


var xdata = [12,35,82,97,49,10,27,8];

// show input list, note the string "<br>" to output newline 
document.write("Unsorted list: ", xdata, "<br>");   

bubble ();          // function call

// show sorted list
document.write("Sorted output list: ", xdata);


// --- function defs ---------------------------------

function bubble()   // simply use the keyword function
{
   var i, j;        // local, not available outside function
   
   var n = xdata.length;
   for (i = 0; i < n-1; i++)    
      for (j = n-1; j > i; j--)
         if ( xdata[j] < xdata[j-1] )
            swap (j, j-1);
}

// ---------------------------------------------------
function swap(a, b)  // args a, b also local
{
   var temp = xdata[a];
   xdata[a] = xdata[b];
   xdata[b] = temp;
}