#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 26 21:29:35 2018
@author: vicky
"""
#快速排序
#先从待排序的数组中找出一个数作为基准数(取第一个数即可),
#然后将原来的数组划分成两部分:小于基准数的左子数组和大于等于基准数的右子数组。
#然后对这两个子数组再递归重复上述过程,直到两个子数组的所有数都分别有序。
#最后返回“左子数组” + “基准数” + “右子数组”,即是最终排序好的数组。
## 实现快排
#def quicksort(nums):
# if len(nums) <= 1:
# return nums
# less = [] #左子数组
# greater = [] #右子数组
# base = nums.pop() #基准数,提取最后一个数且删去
#
# for x in nums: # 对原数组进行划分
# if x < base:
# less.append(x)
# else:
# greater.append(x)
#
# return quicksort(less) + [base] + quicksort(greater) # 递归调用
#
#def main():
# nums = [6,1,2,7,9,3,3,4,5,10,10,8]
# print(quicksort(nums))
#main()
def quick_sort(list):
low = []
mid = []
high = []
if len(list) <= 1: # 递归出口
return list
else:
base = list[0] # 将第一个值做为基准
for i in list:
if i < base: # 将比急转小的值放到low数列
low.append(i)
elif i > base: # 将比基准大的值放到high数列
high.append(i)
else: # 将和基准相同的值保存在基准数列
mid.append(i)
low = quick_sort(low) # 对low数列和high数列继续进行排序
high = quick_sort(high)
return low + mid + high
nums = [6,1,2,7,9,3,3,4,5,10,10,8]
print(quick_sort(nums))