Insertion Sort
The main idea of insertion sort is time to take a list element in the list has been sorted list section compares, and then insert the resulting new sorted list section, eventually sorted list.
For example, the list is to be sorted [49,38,65,97,76,13,27,49], the step of comparing the new list and the list obtained as follows :( segments with the background color is already sorted, red bACKGROUND insertion labels are conducted and exchange element)
1 "" " 2 insertion sort: Select the unsorted list of sub-elements and the front element has been in good order list comparing; 3 (1) Method 1: from front to rear Comparative 4 If the current element sorted element value smaller than the front, the position from the sorted elements of a backward movement, then the current element inserted! 5 Note: !!! forward from the rear when moving rearwardly 6 (2) Second way: forward from 7 if the current element than the front to order the elements last value is small, the exchange position, and then continue a comparison before and, if small, the exchange until most front no element! 8 "" " 9 10 11 # one way: to have good order of elements, from front to back comparator 12 is DEF insert_sort (int_list): 13 is length = len (int_list) 14 IF length <=. 1: return int_list 15 for I in Range (. 1, Length): 16 Item = int_list [I] . 17 for J in Range (I): 18 is IF Item < int_list [J]: . 19 for K in Range (I, J, -1 ): 20 is int_list [K] = int_list [K -. 1 ] 21 is int_list [J] = Item 22 is BREAK 23 is return int_list 24 25 26 is # way: to have good order of the elements from the back comparator 27 DEF insert_sort2 (int_list): 28 length = len (int_list ) 29 if length <= 1: return int_list 30 for i in range(1, length): 31 while i > 0: 32 if int_list[i] < int_list[i - 1]: 33 int_list[i], int_list[i - 1] = int_list[i - 1], int_list[i] 34 i -= 1 35 else: 36 break 37 return int_list 38 39 40 # print(insert_sort([11, 3, 5, 89, 1,23456,87678,2345,4567,0,3,5])) 41 #Print (insert_sort2 ([. 11,. 3,. 5, 89, 1,23456,87678,2345,4567,0,3,5])) 42 is IF the __name__ == ' __main__ ' : 43 is int_str = INPUT ( " Please enter a comma-separated integer >>> " ) .strip () 44 is int_list = [int (I) for I in int_str.split ( " , " )] 45 # Print (insert_sort (int_list)) 46 is Print (insert_sort2 (int_list))