Skip to content

Instantly share code, notes, and snippets.

@mutoo
Last active December 17, 2015 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mutoo/5675436 to your computer and use it in GitHub Desktop.
Save mutoo/5675436 to your computer and use it in GitHub Desktop.
a simple implement of bubble sort to find the n-largest number
var N = 1000;
var arr = [];
for(var i=0;i<N;i++)
arr.push(Math.random()*N);
var target = parseInt(N/2); // set the target the middle number
console.time("the "+target+"-largest number of "+N);
console.time("bubble sort");
for(var i=1;i<N;i++) { // do N-1 times
for(var j=0;j<N-i;j++) {
if(arr[j]<arr[j+1]) {
var tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
console.timeEnd("bubble sort");
console.log("found:"+arr[target]);
console.timeEnd("the "+target+"-largest number of "+N);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment