Nodejs 之冒泡排序

冒泡排序的操作类似逐个滚动的效果,复杂度为O(N方),使用的不算太多,理解起来和使用起来也比较简单,示例代码如下:

var data = [321,3,12,45,22,77,90,12,1,32,34,65,78,25,85,24,96];

function p(arr)
{
	var num = 0;
	for(var i=0;i<(arr.length-1);i++)
	{
		for(var t=0;t<(arr.length-1);t++)
		{
			if(arr[t]>arr[t+1])
			{
				num = arr[t];
				arr[t] = arr[t+1];
				arr[t+1] = num;
			}
		}
	}
}

console.log(data);
p(data);
console.log(data);

运行打印结果

[ 321, 3, 12, 45, 22, 77, 90, 12, 1, 32, 34, 65, 78, 25, 85, 24, 96 ]
[ 1, 3, 12, 12, 22, 24, 25, 32, 34, 45, 65, 77, 78, 85, 90, 96, 321 ]