# inserts a value in ascending order with for loop # @param array list of values # @param right_index int the rightmost index of subarray # @param value int the value to insert def insert(array, right_index, value): for index in xrange(right_index, -2, -1): if value >= array[index]: break array[index + 1] = array[index] array[index+1] = value # inserts a value in ascending order with while loop # @param array list of values # @param right_index int the rightmost index of subarray # @param value int the value to insert def insert(array, right_index, value): index = right_index while index >=0 and value < array[index]: array[index + 1] = array[index] index -= 1 array[index + 1] = value array = [1,2,3,4,5,6,9,10,12] insert(array, 7, 7) print array insert(array, 7, 0) print array array = [0,2] insert(array, 0, 1) print array def insertionSort(array): for index in xrange(1, len(array)): insert(array, index-1, array[index]) array = [1,2,3,4,5,6,9,10,12, 0, -1, 1, 0, -10] insertionSort(array) print array
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question