user5808331
user5808331

Reputation:

Why doesn't this while loop stop?

For some reason I cannot get this code to properly sort. I am replacing out of order numbers in order to make an ordered list.

 var unsortedArray = new Array(1,2,5,4);

    var sortedArray = unsortedArray;
    var tempValue = 0;

    function isSorted(array)
    {
        for (i = 0; i < array.length; i++)
        {
            if (array[i] > array[i+1])
            {
                return false;
            }
        }
        return true;
    }

    function sort(array)
    {



        while (isSorted(array) == false)
        {
            for (i = 0; i < length; i++)
            {
                var tempValue = array[i];

                array[i] = array[i+1];
                array[i+1] = tempValue;
            }
        }
    }

    sort(sortedArray);

    document.write(sortedArray);

The while loop here is supposed to stop when the array is sorted, but that never happens.

Upvotes: 1

Views: 86

Answers (3)

Kajal
Kajal

Reputation: 739

Try this,

It will swap elements only if a[n] is less than a[n-1].

while (isSorted(array) == false)
{
    for (i = 0; i < length-1; i++)
    {
      if(array[i]>array[i+1]){
             var tempValue = array[i];
             array[i] = array[i+1];
             array[i+1] = tempValue;
       }
}

It also changes the for loop to be for(var i = 0; i < length - 1; i++).

Otherwise, at the end of the array, you'll be accessing array[length] which will be undefined(Luckily that wouldn't affect the sorting, but it's better to be correct anyway).

Upvotes: 1

Avijeet Ghosh
Avijeet Ghosh

Reputation: 167

for (i = 0; i < length; i++)
    {
        var tempValue = array[i];

        array[i] = array[i+1];
        array[i+1] = tempValue;
    }

here you never check whether the adjascent values are sorted..... ot the left value is greater than right value....(though i am considering length in the for loop of the sort function to be array length)

Review a simple bubble sort algo and then try.....

refer this algo in C here

Upvotes: 0

Amir Popovich
Amir Popovich

Reputation: 29836

You have a endless loop since this code:

for (i = 0; i < length; i++)
    {
        var tempValue = array[i];

        array[i] = array[i+1];
        array[i+1] = tempValue;
    }

Doesn't sort an array.

Why not use the array.prototype.sort instead?

Upvotes: 2

Related Questions