Skip to content

Commit

Permalink
CLRS7
Browse files Browse the repository at this point in the history
  • Loading branch information
gycg committed Sep 15, 2016
1 parent 083d6d5 commit aee409d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
19 changes: 19 additions & 0 deletions quick_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
def partition(A, p, r):
x = A[r]
i = p-1
for j in xrange(p, r):
if A[j] <= x:
i += 1
A[i], A[j] = A[j], A[i]
A[i+1], A[r] = A[r], A[i+1]
return i+1

def quicksort(A, p, r):
if p < r:
q = partition(A, p, r)
quicksort(A, p, q-1)
quicksort(A, q+1, r)

A = [2, 8, 7, 1, 3, 5, 6, 4]
quicksort(A, 0, 7)
print A
25 changes: 25 additions & 0 deletions randomized_quicksort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
def partition(A, p, r):
x = A[r]
i = p-1
for j in xrange(p, r):
if A[j] <= x:
i += 1
A[i], A[j] = A[j], A[i]
A[i+1], A[r] = A[r], A[i+1]
return i+1

def randomized_partition(A, p, r):
from random import randrange
i = randrange(p, r+1, 1)
A[r], A[i] = A[i], A[r]
return partition(A, p, r)

def randomized_quicksort(A, p, r):
if p < r:
q = randomized_partition(A, p, r)
randomized_quicksort(A, p, q-1)
randomized_quicksort(A, q+1, r)

A = [2, 8, 7, 1, 3, 5, 6, 4]
randomized_quicksort(A, 0, 7)
print A

0 comments on commit aee409d

Please sign in to comment.