Skip to content

Instantly share code, notes, and snippets.

@lbj96347
Created April 30, 2012 17:24
Show Gist options
  • Save lbj96347/2560263 to your computer and use it in GitHub Desktop.
Save lbj96347/2560263 to your computer and use it in GitHub Desktop.
Javascript Bubble Sort
//Javascript 冒泡排序,我把1000个随机数进行无序写入数组后,进行冒泡排序,观察浏览器运算使用时间
//if your browser support Date.now(), You can use Date.now() to get the current time
SortHelper = {
  BubbleSort: function(array,time1) {
    length = array.length;
    for(i=0; i<=length-2; i++) {
      for(j=length-1; j>=1; j--) {
        if(array[j] < array[j-1]) {
          temp = array[j];
          array[j] = array[j-1];
          array[j-1] = temp;
        }
      }
if ( i == 998 ){
var m = new Date();
var time2 = m.getTime();
console.log(time2-time1 + 'ms');
}
    }
  }
}
test = {
  run: function() {
var d = new Date();
var time1 = d.getTime();
var num = new Array();
for( i = 0 ; i < 1000 ; i++ ){
num[i] = Math.floor(Math.floor(Math.random()*1000+1));
}
    array = num;
    SortHelper.BubbleSort(array,time1);
    for(i in array) {
      console.log(array[i]);
    }
//console.log('time1:'+time1);
  }
}
test.run();
@fibjs
Copy link

fibjs commented May 1, 2012


SortHelper = {
    BubbleSort : function(array) {
        length = array.length;
        for (i = 0; i <= length - 2; i++) {
            for (j = length - 1; j >= 1; j--) {
                if (array[j] < array[j - 1]) {
                    temp = array[j];
                    array[j] = array[j - 1];
                    array[j - 1] = temp;
                }
            }
        }
    }
}

test = {
    run : function() {
        var d = new Date();
        var time1 = d.getTime();
        
        for(var j = 0; j < 100; j ++)
        {
            var num = new Array();
            for (i = 0; i < 1000; i++) {
                num[i] = Math.floor(Math.floor(Math.random() * 1000 + 1));
            }
            array = num;
            SortHelper.BubbleSort(array);
        }
        document.write('time1:'+( new Date().getTime() - time1));
    }
}
test.run();

@lbj96347
Copy link
Author

lbj96347 commented May 1, 2012

经过测试,我们可以知道console是很坑爹的。

@fibjs
Copy link

fibjs commented May 1, 2012

这很正常,io 是吃 cpu 大户。所以我拿到代码就把 console 删掉了测的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment