Skip to content

Instantly share code, notes, and snippets.

@selfboot
Created July 27, 2014 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save selfboot/b35ddd0c21b65797dbf3 to your computer and use it in GitHub Desktop.
Save selfboot/b35ddd0c21b65797dbf3 to your computer and use it in GitHub Desktop.
插入排序的python实现。
#! /usr/bin/env python
# -*- coding: utf-8 -*-
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))
count = len(sort_sequence)
start_index = 1
while start_index < count:
#insert sort_sequence[start_index] into the sorted
#sort_sequence[0,start_index-1]
#this insertion operation is hard to understand
"""
for i in range(start_index):
if (sort_sequence[start_index] < sort_sequence[i]):
sort_sequence[start_index], sort_sequence[i] = sort_sequence[i],\
sort_sequence[start_index]
print "start_index: ", start_index, "sequence: ", sort_sequence
else:
continue
start_index += 1"""
#This insertion operation is in the python way
for i in range(start_index):
if (sort_sequence[start_index] < sort_sequence[i]):
temp = sort_sequence[start_index]
sort_sequence[i+1:start_index+1] = \
sort_sequence[i:start_index]
sort_sequence[i] = temp
break
else:
continue
start_index += 1
print sort_sequence
# ➜ algorithm ./insertion_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