Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to sort in Python

What is the fastest way to sort an array of whole integers bigger than 0 and less than 100000 in Python? But not using the built in functions like sort.

Im looking at the possibility to combine 2 sport functions depending on input size.

like image 677
Anders Avatar asked Oct 04 '10 13:10

Anders


People also ask

What is the fastest sorting method Python?

Compared to bubble sort and insertion sort, the merge sort implementation is extremely fast, sorting the ten-thousand-element array in less than a second!

Which is the fastest method of sorting?

If you've observed, the time complexity of Quicksort is O(n logn) in the best and average case scenarios and O(n^2) in the worst case. But since it has the upper hand in the average cases for most inputs, Quicksort is generally considered the “fastest” sorting algorithm.

How do you sort a list quickly in Python?

To sort elements in python, we can use the built-in function sorted() to sort any Python list. It offers the ability to sort data. After writing the above code (python built-in sorting algorithm), once you will print ” s “ then the output will be ”[2, 3, 6, 8, 9, 10] ”.

Is sort () or sorted () faster?

sort is slightly faster than sorted and consumes around 24% less memory. However, keep in mind that list. sort is only implemented for lists, whereas sorted accepts any iterable.


1 Answers

If you are interested in asymptotic time, then counting sort or radix sort provide good performance.

However, if you are interested in wall clock time you will need to compare performance between different algorithms using your particular data sets, as different algorithms perform differently with different datasets. In that case, its always worth trying quicksort:

def qsort(inlist):
    if inlist == []: 
        return []
    else:
        pivot = inlist[0]
        lesser = qsort([x for x in inlist[1:] if x < pivot])
        greater = qsort([x for x in inlist[1:] if x >= pivot])
        return lesser + [pivot] + greater

Source: http://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Python

like image 89
fmark Avatar answered Oct 03 '22 14:10

fmark