Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first 10 sorted items of a list without sorting the whole list

The problem is I have a list of 1 million numbers, but I only want the 10 first of the sorted list, but I do not want to sort the whole list? Is that possible?

like image 826
DogDog Avatar asked Jun 28 '10 19:06

DogDog


People also ask

How do you sort a list in Python without sorting?

You can use Nested for loop with if statement to get the sort a list in Python without sort function. This is not the only way to do it, you can use your own logic to get it done.

How do you sort a list without using sort function?

Python Program to Sort List in Ascending Order without using Sort. In this program, we are using Nested For Loop to iterate each number in a list, and sort them in ascending order. It means the condition is False. So, it exits from the If block, and the j value incremented by 1.

How do you sort a list without modifying it?

If you want to create a new sorted list without modifying the original one, you should use the sorted function instead. As you can notice, both sort and sorted sort items in an ascending order by default.

Does sorted () modify the original list?

The original list is not changed. It's most common to pass a list into the sorted() function, but in fact it can take as input any sort of iterable collection. The older list. sort() method is an alternative detailed below.


2 Answers

Yes. You just run through the list once, and store the ten smallest numbers. The algorithm will be O(n) (actually, O(n*10) worstcase)

Foreach (list)
 - Check if current item is smaller than the biggest item in the sorted Array[10]
 - If so, put the current item at the right spot (sorted) in the array (insertionsort), bumping away the biggest item.
like image 123
Konerak Avatar answered Oct 05 '22 04:10

Konerak


What you want is a Priority Queue. Insert each number into a priority queue. If the size of the queue exceeds 10, then remove the smallest (or largest) value. The values that remain in the queue at the end are the 10 largest (or smallest).

If the queue is implemented using a Heap, then this can be a very effecient algorithm.

like image 21
Jeffrey L Whitledge Avatar answered Oct 05 '22 04:10

Jeffrey L Whitledge