0

I have an array of size n of unsorted integers and I would like to print the smallest t elements from it.

For example, if I have the following array:

int[] input = {5,6,2,5,7,8,9,1,22,64,3,4} 
int t = 5;

Then my result should be:

result = {1,2,3,4,5}

Requested code:

Arrays.sort(input);

for(int i = 0; i <= t; i++) {
    System.out.println(input[i]);
}

Currently how I'm going it is I'm sorting the array using Arrays.sort(), and then iterating through the first t terms to print it. This solves the problem in O(nlgn). However, if I have a an array with a sufficiently large size (n > 1000) then it seems like bad practice to sort the whole thing to get t number of elements (assuming t is much smaller than n).

I was wondering if there is some other data structure in Java which can do it more efficiently? Maybe something that linearly probes the array and creates a smaller array of size t and fills it with the smallest t elements in the original array by utilizing some check?

I was looking into a Priority Queue or a MinHeap but I'm not sure if it solves the problem I'm having, which is to solve it in better than O(nlgn) time.

Do you guys have any ideas?

FlameDra
  • 1,807
  • 7
  • 30
  • 47

0 Answers0