Bubble Sort Numbers

[Total: 0    Average: 0/5]

This routine uses a simple bubble sort algorythm to sort numbers.

Body Code:

<SCRIPT> 
function BubbleSortUp(arrayName,length) 
{ 
    for (var i=0; i<(length-1); i++) 
    { 
        for (var b=i+1; b<length; b++) 
{ 
            if (arrayName[b] < arrayName[i]) 
    { 
                var temp = arrayName[i]; 
                arrayName[i] = arrayName[b]; 
                arrayName[b] = temp; 
    } //end-if 
        } //end for-loop 
    } //end for-loop 
document.write("This sorts small to large." +"<BR>"); 
} // end fn BubbleSortUp 

function BubbleSortDown(arrayName,length) 
{ 
    for (var i=0; i<(length-1); i++) 
    { 
        for (var b=i+1; b<length; b++) 
{ 
            if (arrayName[b] > arrayName[i]) 
    { 
                var temp = arrayName[i]; 
                arrayName[i] = arrayName[b]; 
                arrayName[b] = temp; 
    } //end-if 
        } //end for-loop 
    } //end for-loop 
document.write("This sorts large to small." +"<BR>"); 
} // end fn BubbleSortDown 

function showArray(text,arrayName,length) 
{ 
    document.write(text + ': '); 
    for (var i=0; i<length; i++) 
        {document.write(arrayName[i]+' ');} 
    document.write('<BR>'); 
} //end fn showArray 

var myArray = new Array(440,5,47,9222,11111); 
showArray('Unsorted',myArray,myArray.length); 
BubbleSortDown(myArray,myArray.length); 
showArray('Sorted-Down',myArray,myArray.length); 

var myArray = new Array(440,5,47,9222,11111); 
showArray('Unsorted',myArray,myArray.length); 
BubbleSortUp(myArray,myArray.length); 
showArray('Sorted-Up',myArray,myArray.length); 

document.write("<BR>" +"Using the BUILT-IN SORT method, sorts on each digit, not value."+"<BR>"); 
document.write("This sorts small to large." +"<BR>"); 

var myArray = new Array(440,5,47,9222,11111); 
showArray('Unsorted',myArray,myArray.length); 
myArray.sort(); 
showArray('Sorted-alpha',myArray,myArray.length); 

//HERE'S THE TRICKY PART 

var myArray = new Array(5); 
for (i=0; i<myArray.length; i++) 
{ 
    myArray[i] = (prompt("Input a number. ", "")); 
    //alert ("myArray[" +i +"] " +myArray[i]); 
} 
showArray('<BR><BR>When using prompted input: <BR>Unsorted',myArray,myArray.length); 
BubbleSortUp(myArray,myArray.length); 
showArray('Sorted-Up',myArray,myArray.length); 
BubbleSortDown(myArray,myArray.length); 
showArray('Sorted-Down',myArray,myArray.length); 

document.write("NEW CODE");
for (var i=0;i<myArray.length;i++) myArray[i] = parseInt(myArray[i]);

showArray('<BR><BR>When using prompted input: <BR>Unsorted',myArray,myArray.length); 
BubbleSortUp(myArray,myArray.length); 
showArray('Sorted-Up',myArray,myArray.length); 
BubbleSortDown(myArray,myArray.length); 
showArray('Sorted-Down',myArray,myArray.length); 


</SCRIPT> 

Times Viewed: 3

Leave a Reply

Your email address will not be published. Required fields are marked *