Javascript: Bubble Sort and Math.Random

Sep 3, 2014
We are given an exercise that needs to be solved using Javascript.

*Bubble sort
-ceate a function that returns a sorted array in ascending order
-within the function, create an array with a size of 10 with random unique numbers (1-100) in it (to generate random numbers try using Math.random() function)
-sort the random values then return the array

*displaying the array
-in respect to problem 1, display the returned array into an ordered list element (<ol>)

Here is my solution to the problem.
Code snippets to help with output tracing is also available as comments.

var num = [];

num = assignValToArray();
bubbleSort(num);
displayOrderedList(num);

// ***** FUNCTIONS *****

//assign n random unique numbers to array;
function assignValToArray(){
 var arr = [];
 var val;
 var maxNum = 100;
 var minNum = 1;
 var n = 10; //size;
 
 while(arr.length < n){
  val = Math.floor(Math.random() * ((maxNum + 1) - minNum) + minNum);
  //check generated value if exists in the array;
  var exist = false;
  for(var x = 0; x < arr.length; x++){
   if(val === arr[x]){
    exist = true;
    break;
   }
  }
  
  //push to array if generated value does not exist;
  if(!exist){
   arr.push(val);
  }
 } 
 //document.write("Original list: " + arr); //original list;
 return arr; 
}

// bubble sort;
function bubbleSort(arr){
 //var count = 0; //count for every iteration;
 do{
  var tmp; //hold temporary value;
  var swap = false;
  for(var i = 0; i < arr.length-1; i++){
   if(arr[i] > arr[i+1]){
    swap = true;
    tmp = arr[i];
    arr[i] = arr[i+1];
    arr[i+1] = tmp;
   }
  }
  //count++;
  //document.write("<br>" + count + "th Iteration: " + num); //list every iteration;
 }while(swap);
}

//display output;
function displayOrderedList(arr){
 document.write("<ol>");
 for(var i = 0; i < arr.length; i++){
  document.write("<li>" + arr[i] + "</li>");
 }
 document.write("</ol>");
}

For questions or for better solutions, feel free to leave a message on the comments section.

1 comment: