You have a list of n integers and you want the x smallest. For example,
x_smallest([1, 2, 5, 4, 3], 3)
should return [1, 2, 3]
.
I\'ll v
private static int[] x_smallest(int[] input, int x)
{
int[] output = new int[x];
for (int i = 0; i < x; i++) { // O(x)
output[i] = input[i];
}
for (int i = x; i < input.Length; i++) { // + O(n-x)
int current = input[i];
int temp;
for (int j = 0; j < output.Length; j++) { // * O(x)
if (current < output[j]) {
temp = output[j];
output[j] = current;
current = temp;
}
}
}
return output;
}
Looking at the complexity: O(x + (n-x) * x) -- assuming x is some constant, O(n)