我用Python创建了一个代码,有人能告诉我不使用sort()
对随机数进行排序的算法吗?
import random
firstNum=1
lastNum=30
range=xrange(firstNum,(lastNum))
count=20
print"Random numbers generated:"
numberlist=random.sample(range,count)
print "Before" , numberlist
print('')
numberlist.sort()
print "After" ,numberlist
print('')
答案 0 :(得分:2)
当然,只需使用sorted
:
import random
firstNum = 1
lastNum = 30
range = xrange(firstNum, lastNum)
count = 20
print "Random numbers generated:"
numberlist = random.sample(range, count)
print "Before", numberlist
print('')
numberlist = sorted(numberlist)
print "After", numberlist
print('')
答案 1 :(得分:1)
您可以执行此类不同类型的排序技术。这种技术称为Bubble Sort
和复杂度O(n ^ 2)
def bubbleSort(a):
update=True
while(update):
update = False
for i in range(len(a)-1):
if a[i]>a[i+1]:
a[i],a[i+1]=a[i+1],a[i]
update = True
return a
您还可以通过快速排序技术使用复杂性O(nlogn)
。详情说明在Quick Sort
def quickSort(alist):
quickSortHelper(alist,0,len(alist)-1)
def quickSortHelper(alist,first,last):
if first<last:
splitpoint = partition(alist,first,last)
quickSortHelper(alist,first,splitpoint-1)
quickSortHelper(alist,splitpoint+1,last)
def partition(alist,first,last):
pivotvalue = alist[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and \
alist[leftmark] <= pivotvalue:
leftmark = leftmark + 1
while alist[rightmark] >= pivotvalue and \
rightmark >= leftmark:
rightmark = rightmark -1
if rightmark < leftmark:
done = True
else:
temp = alist[leftmark]
alist[leftmark] = alist[rightmark]
alist[rightmark] = temp
temp = alist[first]
alist[first] = alist[rightmark]
alist[rightmark] = temp
return rightmark
alist = [54,26,93,17,77,31,44,55,20]
quickSort(alist)
print(alist)
答案 2 :(得分:0)
有各种各样的排序实现。它们的区别在于它们的空间和时间复杂性及其附带的好处。
这个问题太笼统,无法给出具体的答案,但我们可以给你一些指示。
考虑一下:
考虑一下这个link,它可以很好地介绍基本的python排序算法,或者使用Stack Overflow上的搜索功能来查找有关这些算法的更多信息。