www.webdeveloper.com
Results 1 to 2 of 2

Thread: JavaScript bubble sort

  1. #1
    Join Date
    May 2013
    Posts
    1

    JavaScript bubble sort

    If some one can tell me what the mistake is,it will only show the unsorted array but not the sorted array please help
    heres the code:


    <HTML>
    <HEAD>
    <TITLE>
    bubblesort
    </TITLE>
    <SCRIPT language = "JavaScript">


    var bubblesort=function(array){
    if(arguments.length===0||!Array.isArray(array)){
    throw new Error();
    }
    var hadhaschange;
    for(var i=1; i<array.length-1;i++){
    hadhaschange=false;

    for(var j=0;j<array.length-1;j++){
    if(array[j]> array[j+1])
    {
    hadhaschange=true;
    var temp=array[j];
    array[j]=array[j+1];
    array[j+1]=temp;
    }
    }
    if(!hashadchange){
    return array;
    }
    }
    return array;
    }
    function bubbleTest()
    {
    var unsortedArray;
    var sortedArray;

    // array to be ordered
    unsortedArray = [9,7,2,10,1,4,8,6,5,3];

    document.write('Unsorted Array: ' + unsortedArray + '<BR>');

    document.write('Sorted Array: ' + bubblesort(unsortedArray));
    }

    // invoke bubbleTest() to test function bubblesort()
    bubbleTest();



    </SCRIPT>
    </HEAD>
    <BODY>

    </BODY>
    </HTML>

  2. #2
    Join Date
    Sep 2007
    Location
    istanbul
    Posts
    315
    hashadchange is not defined
    line 26

    I change this
    if(!hashadchange){

    to this
    if(!hadhaschange){

    your code is working.

    My code is here:
    Code:
      
    <HTML>
    <HEAD>
    <TITLE>
    bubblesort
    </TITLE>
    <SCRIPT type="text/javascript">
    
    // http://www.webdeveloper.com/forum/showthread.php?277857-JavaScript-bubble-sort
    
    
    var unsortedArray = [9,7,2,10,1,4,8,6,5,3];
    var sortedArray= [];
    var i;
    var t;
    for(i=0; i< unsortedArray.length; i++) {
    t = unsortedArray[i];
     sortedArray[t-1] = t;
    }
    // alert(sortedArray);
    
    
    
    document.write('Unsorted Array: ' + unsortedArray + '<BR>');
    
    document.write('Sorted Array: ' + sortedArray );
    
    
    
    </SCRIPT>
    </HEAD>
    <BODY>
    
    </BODY>
    </HTML>
    Last edited by Ayşe; 05-13-2013 at 02:14 AM.
    Bismillahirrahmanirrahîm
    Hamd, Âlemlerin Rabbi, Rahmân, Rahîm, hesap ve ceza gününün (ahiret gününün) maliki Allah'a mahsustur. (Allahım!) Yalnız sana ibadet ederiz ve yalnız senden yardım dileriz. Bizi doğru yola, kendilerine nimet verdiklerinin yoluna ilet; gazaba uğrayanların ve sapıklarınkine değil.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles