首先是:冒泡排序
实现思路:其实简单的来说就是,拿第一个跟第二个进行比较,如果第二个比第一个大,那么互换他们的位置,
然后拿第二个跟第三个比较,如果第三个比第二个大,那么互换他们的位置,
这样依次比较,由此我们可以得知,完成一轮之后,最后一个肯定是最大的!
然后通过for循环来完成排序;
var str = [1, 33, 44, 66, 22, 11,44, 31, ] for(var i = 0; i < str.length - 1; i++) { for(var j = 0; j < str.length - 1 - i; j++) { if(str[j] > str[j + 1]) { var t = str[j]; str[j] = str[j + 1]; str[j + 1] = t } } } console.log(str)
然后是:选择排序
实现思路:跟冒泡排序恰恰相反,看完上面的冒泡排序我们可以得知,冒泡排序是先将最大的排到最后;
而选择排序则是先将最小的排到最前面;
var str = [1, 33, 44, 66, 22, 11,44, 31 ] for(var j=0;j<str.length;j++){ for(var i=j+1;i<str.length;i++){ if(str[j]>str[i]){ var t = str[j] str[j] = str[i] str[i] = t } } } console.log(str)