Skip to content

Instantly share code, notes, and snippets.

@selfboot
Created July 27, 2014 04:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save selfboot/4bd7be8d72de34ba8d21 to your computer and use it in GitHub Desktop.
Save selfboot/4bd7be8d72de34ba8d21 to your computer and use it in GitHub Desktop.
快速排序的python实现
#! /usr/bin/env python
# -*- coding: utf-8 -*-
def quick_sort(sequence, start_index, end_index):
# print sequence
if start_index < end_index:
main_element = partition(sequence, start_index, end_index)
# print main_element
quick_sort(sequence, start_index, main_element-1)
quick_sort(sequence, main_element+1, end_index)
else:
pass
def partition(sequence, start_index, end_index):
middle_value = sequence[end_index]
mark_index = start_index - 1
scan_index = start_index
while scan_index < end_index:
if sequence[scan_index] < middle_value:
mark_index += 1
sequence[scan_index], sequence[mark_index] = \
sequence[mark_index], sequence[scan_index]
else:
pass
scan_index += 1
sequence[end_index], sequence[mark_index+1] = \
sequence[mark_index+1], sequence[end_index]
return mark_index+1
if __name__ == '__main__':
original_sequence = raw_input("Enter the sequence: ")
sequence_str = original_sequence.split()
sort_sequence = []
for number_str in sequence_str:
sort_sequence.append(int(number_str))
size = len(sort_sequence)
quick_sort(sort_sequence, 0, size-1)
print sort_sequence
"""
➜ algorithm ./quick_sort.py
Enter the sequence: 90 89 09 32 4 5 76 8999 32 43554 6576 090
[4, 5, 9, 32, 32, 76, 89, 90, 90, 6576, 8999, 43554]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment