J4mbo / algorithm-study

0 stars 0 forks source link

quick sort #1

Open cookk opened 6 years ago

cookk commented 6 years ago
cookk commented 6 years ago

def partition_sort(arr, start_loc, end_loc): if start_loc >= end_loc: return

pivot_loc = pick_pivot(start_loc, end_loc)

arr[pivot_loc], arr[end_loc] = arr[end_loc], arr[pivot_loc]
pivot_loc = end_loc

greater_loc, lesser_loc = get_greater_lesser_loc(arr, start_loc, end_loc, pivot_loc)
if has_greater_num(greater_loc):
    while greater_loc < lesser_loc:
        arr[greater_loc], arr[lesser_loc] = arr[lesser_loc], arr[greater_loc]
        greater_loc, lesser_loc = get_greater_lesser_loc(arr, start_loc, end_loc, pivot_loc)

    arr[greater_loc], arr[pivot_loc] = arr[pivot_loc], arr[greater_loc]
    pivot_loc = greater_loc

partition_sort(arr, start_loc, pivot_loc - 1)
partition_sort(arr, pivot_loc + 1, end_loc)
return arr

def get_greater_lesser_loc(arr, start_loc, end_loc, pivot_loc): greater_loc = get_greater_loc(arr, start_loc, end_loc, pivot_loc) lesser_loc = get_lesser_loc(arr, start_loc, end_loc, pivot_loc) return greater_loc, lesser_loc

def has_greater_num(greater_loc): if greater_loc == -1: return False return True

def get_greater_loc(arr, start_loc, end_loc, pivot_loc): for i in range(start_loc, end_loc): if arr[i] > arr[pivot_loc]: return i return -1

def get_lesser_loc(arr, start_loc, end_loc, pivot_loc): for i in range(end_loc, start_loc - 1, -1): if arr[i] < arr[pivot_loc]: return i return -1

def pick_pivot(start_loc, end_loc): return start_loc

return end_loc

return any_loc


- test
```python
import random

test_arr = list(range(0, 30))
random.shuffle(test_arr)
print("before : {}".format(test_arr))
test_arr = quick_sort(test_arr)
print("after : {}".format(test_arr))