1. Reference
A gitbook online book on sorting Algorithms, "Ten classic Sorting Algorithms", using JavaScript & Python & Go
2. Bubble Sort: 22 comparison, swap position
arr = [9,8,2,23,3]#Bubble sort 22 comparison, swap position#3 5 9) 1 8#A B C D E#3 5 9) 1 8#3 5 9) 1 8#3 5 1) 9 8#3 5 1) 8 9#The first round compares the maximum number of rows to the last, and 5 numbers require a total of 4 rounds i.e. 1,2,3,4#comparison is arr[j] > arr[j+1], the first round of J takes the first 4 number is the range (4) can be, the second round J take the first 3 number range (3) can be#5 Numbers Total comparison 4 3 2 1 = 10 timesdefBubble_sort (arr):Print 'Bubble_sort:', arr Count=0 forIinchRange (1, Len (arr)): forJinchRange (len (arr)-i): Count+ = 1ifARR[J] > Arr[j+1]: arr[j], arr[j+1] = arr[j+1], Arr[j]Print 'bubble_sorted:', Count, Arrbubble_sort ([9,8,2,23,3]) #bubble_sort ([Int (i) for I in Raw_input (': '). Split ()])
2. Select sort: Find the extremum and change to the team head
#3 5 9) 1 8#A B C D EdefSelect_sort (arr): Count=0 forIinchRange (len (arr)-1):#4 min or max total requiredarr_min = Min (arr[i:])#the number removed is easier to handle at the top of the columnArr.remove (arr_min) Arr.insert (i, arr_min)#Note Insert Location update Printarr#Select_sort (arr[:])#Five numbers need 4 rounds#0-bit and 1,2,3,4 comparison, small immediately change to 0 bit#1-bit and 2,3,4 comparison, small immediately change to 1 bitdefSelect_sort1 (arr): Count=0 forIinchRange (len (arr)-1): forJinchRange (i+1, Len (arr)): Count+ = 1ifArr[i] > Arr[j]:#Note Arr[i] has been updatedArr[i], arr[j] =Arr[j], Arr[i]PrintCountPrintarr#Select_sort1 (arr[:])defSelect_sort2 (arr):Print 'Select_sort2:', arr Count=0 forIinchRange (len (arr)-1): Min_index=I forJinchRange (i+1, Len (arr)): Count+ = 1ifArr[min_index] >Arr[j]: Min_index=J Arr[i], Arr[min_index]= Arr[min_index], arr[i]#after a round of update arr[i] Print 'select_sort2ed:', Count, Arrselect_sort2 ([9,8,2,23,3])
3. Insert sort: Play cards, row + no row, insert one by one (binary optimized)
#3 5 9) 1 8#A B C D E#a sorted, bcde not sorted#ab sorted, CDE not sorteddefInsert_sort (arr):Print 'Insert_sort:', arr Count=0 forIinchRange (1, len (arr)):#operand is b forJinchRange (0,i):#operand is aCount + = 1Print 'B', Arr[i],'A', Arr[j], arrifArr[i] <Arr[j]: Arr.insert (J, Arr[i]) arr.pop (i+1)#Insert First, cause the position to be removed is postponed by 1 bits Printarr Break Print 'insert_sorted:', Count, Arrinsert_sort([9,8,2,23,3])
Python Sort algorithm Bubble, select, insert