本文实例讲述了Python实现返回数组中第i小元素的方法。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
#! /usr/bin/env python #coding=utf-8 #期望为线性时间的选择算法 import random class RandomSelect( object ): def Partition( self ,a, p, r): x = a[r] i = p - 1 for j in range (p, r): '''如果a[j]>x,则只需将j的值加1即可使循环不变量继续保持; 如果a[j]<=x,则将下标i的值加1,并交换a[i]和a[j],再将 j的值加1.此时循环不变量同样得到保持''' if a[j]< = x: i = i + 1 a[i], a[j] = a[j], a[i] a[i + 1 ], a[r] = a[r], a[i + 1 ] return i + 1 def RandomPartition( self ,a, p, r): i = random.randint(p, r) #生成的随机数为p=<i<=r a[r], a[i] = a[i], a[r] return self .Partition(a, p, r) def randomSelect( self ,a,p,r,i): if p = = r: return a[p] q = self .RandomPartition(a,p,r) k = q - p + 1 if i = = k: return a[q] elif i<k: return self .randomSelect(a,p,q - 1 ,i) else : return self .randomSelect(a,q + 1 ,r,i - k) if __name__ = = '__main__' : print "服务器之家测试结果:" a = [random.randint( 0 , 20 ) for i in range ( 10 )] print a #a=sorted(a) #print a r = RandomSelect() r.randomSelect(a, 0 , len (a) - 1 , 3 ) print a[ 2 ] #数组中的第三小的数 a = sorted (a) print a |
运行结果:
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://blog.csdn.net/will130/article/details/45244649