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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With