Last active
December 17, 2015 21:29
-
-
Save mutoo/5675436 to your computer and use it in GitHub Desktop.
a simple implement of bubble sort to find the n-largest number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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