-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathQuick3way.py
49 lines (38 loc) · 1.09 KB
/
Quick3way.py
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
44
45
46
47
48
49
#! usr/bin/pyhton
# -*- coding: utf-8 -*-
"""
Quicksort with 3-way.
It perform much better than standard quick sort while sorting an array with lots
of repeating elements.
三向切分的快速排序。
对于存在大量重复元素的数组,这种方法比标准的快速排序的效率高得多。
"""
def quick3way(array):
def sort(lo, hi):
if hi <= lo: return
lt = lo
i = lo + 1
gt = hi
v = array[lo]
while i <= gt:
if array[i] < v:
array[lt], array[i] = array[i], array[lt]
lt += 1
i += 1
elif array[i] > v:
array[i], array[gt] = array[gt], array[i]
gt -= 1
else:
i += 1
sort(lo, lt - 1)
sort(gt + 1, hi)
sort(0, len(array)- 1)
return array
if __name__ == "__main__":
import sys
sys.path.append('../')
from generator import *
data = getRandomNumbers(0, 1000, 15)
print('Quick-three-way Sort')
print('> input: %s' % data)
print('> output: %s' % quick3way(data))