Last active
December 16, 2015 10:08
-
-
Save ialex32x/5417733 to your computer and use it in GitHub Desktop.
Python.QSort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import random | |
data = [1,2,3,4,5,6,7,8,9,0,11,12,13,14,15,16] | |
def randomize(data): | |
for i in xrange(0,len(data)*10): | |
idx1 = random.randint(0, len(data)-1) | |
idx2 = random.randint(0, len(data)-1) | |
if idx1!=idx2: | |
tmp = data[idx1] | |
data[idx1] = data[idx2] | |
data[idx2] = tmp | |
def bubbleSort(data): | |
for i in xrange(0, len(data)): | |
for j in xrange(i, len(data)): | |
if data[i]>data[j]: | |
tmp = data[i] | |
data[i] = data[j] | |
data[j] = tmp | |
def partitions(data, start, end): | |
pivotdata = data[start] | |
while start<end: | |
while start<end and data[end]>=pivotdata: | |
end -= 1 | |
data[start] = data[end] | |
while start<end and data[start]<=pivotdata: | |
start += 1 | |
data[end] = data[start] | |
data[start] = pivotdata | |
return start | |
def quickSort(data, start=0, end=len(data)-1): | |
if start<end: | |
pivot = partitions(data, start, end) | |
quickSort(data, start, pivot) | |
quickSort(data, pivot+1, end) | |
randomize(data) | |
print "randomize:\t%s" % data | |
bubbleSort(data) | |
print "bubbleSort:\t%s" % data | |
randomize(data) | |
print "randomize:\t%s" % data | |
quickSort(data) | |
print "quickSort: \t%s" % data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment