Javascript: buble sort implementation

Bubble sort is by using a flag in a while loop to determine if the given list is sorted or not. Each loop will bubble up the largest value(smallest value for descending order) of the remaining unsorted elements to the correct position. Bubble up means the swap of two values, when looping through each element in the list, if the value of the current position is larger than the value of the next position, swap them and set the swapped flag to true, so that the next outer while loop will loop through list again to do the next round of bubbling. Each inner loop will bubble up one value to the correct position, thus the number of inner loops will decrease by 1 in the next iteration.
Here is an example of bubble sort in Javascript

function bubbleSort(data)
{
	var length = data.length;
	var tmp;
	var swapped=true;
	while(swapped)
	{
		swapped=false;
		for(var i=0; i<length-1; i++)
		{
			if(data[i]>data[i+1])
			{
				temp=data[i];
				data[i]=data[i+1];
				data[i+1]=temp;
				swapped=true;
			}
		}
	}

	return data;
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search