mutoo
5/30/2013 - 2:43 AM

a simple implement of bubble sort to find the n-largest number

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);

function bubbleSort(arr) {
	for (var i = 1; i < N; i++) { // do N-1 times
		for (var j = 0; j < N - i; j++) {
			if (arr[j + 1] < arr[j]) {
				var tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;
			}
		}
	}
}

console.time("the " + target + "-largest number of " + N);
console.time("bubble sort");
bubbleSort(arr);
console.timeEnd("bubble sort");
console.log("found:" + arr[target]);
console.timeEnd("the " + target + "-largest number of " + N);