Data structures and algorithms - sorting algorithm - Selection Sort

 ################## selection sort #######################

"" " 
Select the sort 
idea is kind of how? 
Now there is a sequence: alist = [54,226,93,17,77,31,44,55,20] 
first traversal of all, n is one, the youngest put at the head , alist = [17, 54,226,93,77,31,44,55,20] 
and the rest of the traverse, n-1 th, to the smallest to the front, alist = [17,20 54,226,93,77 , 31,44,55] 
and has been circulating, the end, the entire sequence is a small hit, 


the program to realize 
the first round, the index of the most minimum value of 0, min = 0, then the traversal, the face it began to do a small exchange, alist [0], alist [ 3] = alist [3], alist [0] 
the second round, the subscript of the most minimum value of 1, min = 1, then traversing, in case to give it a small began in exchange, alist [1], alist [ 8] = alist [8], alist [0] 
the third round, the most minimum value of the subscript 2, min = 2, then traverse , the encounter started doing it small exchange, alist [2], alist [ 5] = alist [5], alist [0] 
so the whole idea is to put the whole sequence is divided into two parts, is always put back go to the front of the smallest, 


"" "

 

################## selection sort #######################

# First Edition: 
DEF selection_sort (alist): 
    n-= len (alist) 
    # n-1 times required for selection operation 
    for I in Range (n-1): 
        # minimum recording position 
        min_index I = 
        # i + 1 from the position to the end of the selected minimum data 
        for J in Range (I +. 1, n-): 
            IF alist [J] <alist [min_index]: 
                min_index = J 
        # if the selected data is not in the correct position, exchange 
        alist [i], alist [ min_index] = alist [min_index], alist [I] 

# second Edition: 
DEF selection_sort2 (alist): 
    n-= len (alist) 
    # n-1 times required for selection operation 
    for I in Range (n-1): 
        # record minimum position 
        min_index = I 
        # to the end i + 1 selected from the minimum position data 
        for j in range (i + 1 , n):
            IF alist [J] <alist [min_index]: 
                min_index = J 
        # if the selected data is not in the correct position, the exchange 
        IF min_index = I:! 
            alist [I], alist [min_index] = alist [min_index], alist [I ] 


IF the __name__ == '__main__': 
    alist = [54,226,93,17,77,31,44,55,20] 
    Print (alist) 
    selection_sort (alist) 
    Print (alist)

 

 

################## selection sort #######################

 

################## selection sort #######################

################## selection sort #######################

Guess you like

Origin www.cnblogs.com/andy0816/p/12348379.html