Bubble sort algorithm to achieve -python

 
1
'' ' 2 Bubble Sorting Algorithm Optimization three basic features of a bubble sort is the only exchange of adjacent elements. 4 from the start border, single pass down to the top of the maximum value of the current can be on the boundary; 5 , if the switching operation does not occur, it indicates that the array is ordered. 6 '' ' . 7 . 8 . 9 # algorithm a: substantially bubble sort 10 DEF BubbleSort_1 (ARR): . 11 # outer loop accumulated sorted several rounds, while controlling the upper boundary of the array to be sorted, i.e. A [0..i] is be sorted portion 12 # of the inner loop scanning a [0..i-1], comparing adjacent elements, and by the top of the exchange element value to the maximum value of the top 13 is for I in Range (len (ARR) -. 1 , 0, -1 ): 14 for J in Range (I): 15 IF ARR [J]> ARR [J +. 1 ]: 16 ARR [J], ARR [J +. 1] = ARR [J +. 1 ], ARR [J] . 17 Print ( ' % d of secondary sorting results: ' % (. 8-I), End = '' ) 18 is for J in Range (len (ARR)): . 19 Print ( ' % 3D ' % ARR [J]) 20 is 21 is 22 is # algorithm II: improved bubble sort, the exchange operation flag set 23 is DEF BubbleSort_2 (ARR): 24 for I in Range (len (ARR) -. 1, 0, -1 ): 25 In Flag = False # assume without making the switching operation 26 for J in Range (0, I): 27 IF ARR [J]> ARR [J +. 1 ]: 28 ARR [J], ARR [J +. 1] = ARR [J +. 1 ], ARR [J] 29 In Flag True = # set interworking flag 30 IF not in flag: 31 is BREAK # no exchange operation has been completed represents sorted, exit the loop 32 33 is 34 is # algorithm II: bidirectional bubble (cocktail sort), since the area of the exchange operation is not occurring sequence, you can update round down scanning upper and lower boundaries, reducing the scanning range 35 DEF BubbleSort_3 (ARR): 36 Low, High = 0, len (ARR) -. 1 37 [ the while Low < High: 38 is Low = swapPos # assume the position of the switching operation for the last occurrence Low 39 for J in Range (Low, High): # sequential scanning A [-low..high. 1] 40 IF ARR [J]> ARR [J +. 1 ]: 41 is ARR [J], ARR [J +. 1] = ARR [J +. 1 ], ARR [J] 42 is swapPos = J 43 is High = swapPos # modify the boundary to be sorted array is the position switching operation of last occurrence 44 is for J in Range (High, Low, -1): # reverse scan A [Low 1..high +] 45 IF ARR [J] <ARR [J -. 1 ]: 46 is ARR [J], ARR [J -. 1] = ARR [J -. 1 ], ARR [J] 47 swapPos = J 48 Low = swapPos # modify the lower bound of the array to be sorted for the location of the swap operation last occurrence

 

Guess you like

Origin www.cnblogs.com/liangxfng/p/11537391.html