1
-
2
-
3
-
4
- def quickSelect (array , k ):
1
+ def quickselect (array , k ):
5
2
position = k - 1
6
- return quickSelectHelper (array , 0 , len (array ) - 1 , position )
7
-
8
-
9
- def quickSelectHelper (array , startIndex , endIndex , position ):
10
- while True :
11
- if startIndex > endIndex :
12
- raise Exception ('Algorithm should never arrive here!' )
13
- pivotIndex = startIndex
14
- leftIndex = startIndex + 1
15
- rightIndex = endIndex
16
- while leftIndex <= rightIndex :
17
- if array [leftIndex ] > array [pivotIndex ] and array [rightIndex ] < array [pivotIndex ]:
18
- swap (leftIndex , rightIndex , array )
19
- if array [leftIndex ] <= array [pivotIndex ]:
20
- leftIndex += 1
21
- if array [rightIndex ] >= array [pivotIndex ]:
22
- rightIndex -= 1
23
- swap (pivotIndex , rightIndex , array )
24
- if rightIndex == position :
25
- return array [rightIndex ]
26
- elif rightIndex < position :
27
- startIndex = rightIndex + 1
28
- else :
29
- endIndex = rightIndex - 1
30
-
3
+ return quickSelectHelper (array , 0 , len (array ) - 1 , position )
31
4
32
- def swap (one , two , array ):
33
- array [one ], array [two ] = array [two ], array [one ]
5
+ def quickSelectHelper (array , srtIdx , endIdx , position ):
6
+ while True :
7
+ if srtIdx > endIdx :
8
+ raise Exception ("Algorrithm should never be here!" )
9
+ pivotIdx = srtIdx
10
+ leftIdx = srtIdx + 1
11
+ rightIdx = endIdx
12
+ while leftIdx <= rightIdx :
13
+ if array [leftIdx ] > array [pivotIdx ] > array [rightIdx ]:
14
+ array [leftIdx ], array [rightIdx ] = array [rightIdx ], array [leftIdx ]
15
+ if array [leftIdx ] <= array [pivotIdx ]:
16
+ leftIdx += 1
17
+ if array [rightIdx ] >= array [pivotIdx ]:
18
+ rightIdx -= 1
19
+ array [pivotIdx ], array [rightIdx ] = array [rightIdx ], array [pivotIdx ]
20
+ if rightIdx == position :
21
+ return array [position ]
22
+ elif rightIdx > position :
23
+ endIdx = rightIdx - 1
24
+ else :
25
+ srtIdx = rightIdx + 1
0 commit comments