Fastest way to sort in Python

后端 未结 9 2080
太阳男子
太阳男子 2021-02-13 02:56

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 th

相关标签:
9条回答
  • 2021-02-13 03:08

    The built in functions are best, but since you can't use them have a look at this:

    http://en.wikipedia.org/wiki/Quicksort

    0 讨论(0)
  • 2021-02-13 03:21
    def sort(l):
        p = 0
        while(p<len(l)-1):
            if(l[p]>l[p+1]):
                l[p],l[p+1] = l[p+1],l[p]
                if(not(p==0)):
                    p = p-1
            else:
                p += 1
        return l
    

    this is a algorithm that I created but is really fast. just do sort(l) l being the list that you want to sort.

    0 讨论(0)
  • 2021-02-13 03:25

    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

    0 讨论(0)
提交回复
热议问题