Python实现桶排序与快速排序算法结合应用示例

本文实例讲述了Python实现桶排序与快速排序算法结合应用的方法。分享给大家供大家参考,具体如下:

#-*- coding: UTF-8 -*-

import numpy as np

from QuickSort import QuickSort

def BucketSort(a, n):

barrel = {}

for i in xrange(0,n):

barrel.setdefault(i, [])

min = np.min(a)

max = np.max(a)

for x in a:

for i in xrange(0,n-1):

if x >= min +i* (max - min)/n and x < min +(i +1) * (max - min)/n:

barrel[i].append(x)

elif i == n-2 and x >= min +(i +1) * (max - min)/n:

barrel[i+1].append(x)

k = 0

for i in xrange(0,n):

if len(barrel[i]) != 0:

arr = np.array(barrel[i])

QuickSort(arr, 0, len(barrel[i]) -1)

for x in arr:

a[k] = x

k += 1

if __name__ == '__main__':

a = np.random.randint(0, 100, size = 10)

print "Before sorting..."

print "---------------------------------------------------------------"

print a

print "---------------------------------------------------------------"

BucketSort(a, 10)

print "After sorting..."

print "---------------------------------------------------------------"

print a

print "---------------------------------------------------------------"

快速排序QuickSort:

#-*- coding: UTF-8 -*-

import numpy as np

def Partition(a, i, j):

x = a[i] #将数组的第一个元素作为初始基准位置

p = i #同时记录下该元素的位置

while i < j:

while i < j and a[j] >= x:

j -= 1

while i < j and a[i] <= x:

i += 1

if i != j:

a[i], a[j] = a[j], a[i] #交换a[i]与a[j]

a[p], a[i] = a[i], a[p] #将a[p]与a[i]进行交换

p = i #得到分隔位置

return p

def QuickSort(a, i, j):

if i < j:

p = Partition(a, i, j)

QuickSort(a, i, p-1)

QuickSort (a, p+1, j)

if __name__ == '__main__':

a = np.random.randint(0, 100, size = 100)

print "Before sorting..."

print "---------------------------------------------------------------"

print a

print "---------------------------------------------------------------"

QuickSort(a, 0, a.size - 1)

print "After sorting..."

print "---------------------------------------------------------------"

print a

print "---------------------------------------------------------------"

程序运行结果:

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

以上是 Python实现桶排序与快速排序算法结合应用示例 的全部内容, 来源链接: utcz.com/z/357341.html

回到顶部