Python--递归和快速排序 -- quickSort

1.递归
在函数内部再调用本身

2.斐波那契数列
0,1,1,2,3,5,8….
方法一:(普通递归)
def fib(n):
if n=0:
return 0
elif n<=2:
return 1
else:
return fib(n-1)+fib(n-2)

方法二:(匿名函数递归)
fib=lambda n,x=0,y=1:x if n==0 else fib(n-1,y,x+y)

方法三:(迭代)
def fib(n):
x,y=0,1
while(n):
n,x,y=n-1,y,x+y
return x

3.快速排序
每次将数组的最后一个字符取出,将剩下的字符,以大小为比较,放在取出字符的两侧,以此迭代。

#encoding:utf-8
import time
import random
loop_times=1000000
nums=10
A=[random.randint(1,100) for i in xrange(nums)]


def time_cost(times):
    def decorator(f):
        def _f(*args,**kwargs):
            start=time.clock()
            for i in xrange(times):
                a=f(*args,**kwargs)
            end=time.clock()
            print(f.__name__+' run '+str(loop_times)+' times costs '+str(end-start)+' seconds.')
            return a
        return _f
    return decorator

def partition(A,p,r):
    i=p-1
    x=A[r]
    for j in xrange(p,r):
        if A[j]<=x:
            i+=1
            A[i],A[j]=A[j],A[i]
    A[i+1],A[r]=A[r],A[i+1]
    # print(A)
    return i+1

# partition(A,0,len(A)-1)

# @time_cost(loop_times)
def quickSort(A,p=0,r=len(A)-1):
    if r-p>0:
        place=partition(A,p,r)
        quickSort(A,p,place-1)
        quickSort(A,place+1,r)
    return A

@time_cost(loop_times)
def s(A):
    return sorted(A)

print(A)
print(s(A))
# print(quickSort(A))
start=time.clock()
for i in xrange(loop_times):
    a=quickSort(A)
end=time.clock()
print(a)
print('quickSort run '+str(loop_times)+' times costs '+str(end-start)+' seconds.')

打印结果

[26, 39, 4, 41, 73, 59, 2, 29, 74, 59]
s run 1000000 times costs 0.994295 seconds.
[2, 4, 26, 29, 39, 41, 59, 59, 73, 74]
[2, 4, 26, 29, 39, 41, 59, 59, 73, 74]
quickSort run 1000000 times costs 16.131653 seconds.

可见,用了迭代的快速排序效率远不如python内置的排序方式。
迭代排序只是比冒泡排序要快。

def bubbleSort(A):
for i in xrange(len(A),1,-1):
for j in xrange(j-1):
if A[j]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值