Muhammad Ramshad
Muhammad Ramshad

Reputation: 3

Buuble sort to find five most smallest element in an array

I have an array list with some integer values, and I need to find only the five smallest element from the list. Is it efficient to use bubble sort than using any other sorting algorithm? or what is the best algorithm for this?

Upvotes: 0

Views: 167

Answers (1)

Marcelo Cantos
Marcelo Cantos

Reputation: 185902

The common approach is to use a binary heap to track the n smallest elements while scanning from one end to the other.

However, for five elements, it might be just as efficient to track the five smallest seen so far in a simple array. For each new element you inspect, if it's smaller than all the elements in the array, replace the largest with the new element.

Upvotes: 1

Related Questions