Skip to content

Instantly share code, notes, and snippets.

@jinwolf
Last active November 26, 2015 15:41
Show Gist options
  • Select an option

  • Save jinwolf/2558bcf56c421eee5bd7 to your computer and use it in GitHub Desktop.

Select an option

Save jinwolf/2558bcf56c421eee5bd7 to your computer and use it in GitHub Desktop.
A function that returns top K numbers from an integer array
/*
* It gets an array of top k maximum or minimum elements from the given integer array
* For example, findFirstK([2, 10, 1, 3, 4 ,6, 7], 3) returns [10, 7, 6], the top 3 maximum values from the array in the descending order
* or findFirstK([2, 10, 1, 3, 4, 6, 7], 3, true) return [1, 2, 3]
*/
function shift(arr, k, value, asc) {
if (k > arr.length - 1) {
return;
}
var exp = value > arr[k];
if (asc) {
exp = value < arr[k];
}
if (!arr[k] || exp) {
var count = arr.length - 1;
while(count > k - 1) {
arr[count] = arr[count - 1];
count--;
}
arr[k] = value;
} else {
shift(arr, ++k, value, asc);
}
}
module.exports = {
findFirstK: function (int_list, k, asc) {
// find max
var max = new Array(k);
max[0] = int_list[0];
for (var i = 1;i < int_list.length;i++) {
shift(max, 0, int_list[i], asc);
}
return max;
}
};
var findK = require('./find_first_k');
var size = 50000000;
var int_list = new Array(size);
for (var i =0; i < size; i++) {
int_list[i] = i;
}
var time = process.hrtime();
int_list.sort(function(a, b) {
return b - a;
});
console.log([int_list[0], int_list[1], int_list[2]]);
console.log(hrtime(time));
var time = process.hrtime();
var top3 = findK.findFirstK(int_list, 3);
console.log(top3);
console.log(hrtime(time));
//var bottom3 = findK.findFirstK(int_list, 3, true);
//console.log(bottom3);
function hrtime(startAt) {
if (!startAt) {
return process.hrtime();
}
var diff = process.hrtime(startAt);
return diff[0] * 1e3 + diff[1] * 1e-6;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment