Python write a bubble sort

Bubble Sort

introduce:

  Bubble sort (Bubble Sort, Taiwan translated as: bubble sort or bubble sort) is a simple sorting algorithm . It repeatedly walks through the sequence to be sorted, comparing two elements at a time, and swapping them if they are in the wrong order. The work of visiting the sequence is repeated until no more exchanges are needed, that is, the sequence has been sorted. The name of this algorithm comes from the fact that the smaller elements are slowly "floated" to the top of the sequence by swapping.

step:

  1. Compare adjacent elements. If the first is bigger than the second, swap the two of them.
  2. Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number.
  3. Repeat the above steps for all elements except the last one.
  4. Keep repeating the above steps for fewer and fewer elements each time, until there are no pairs of numbers to compare.

#Use the bubble sort method for a set of arrays, sort the numbers inside the array, and output the largest number #Define a set of arrays 
list = [2,31,42,21,6,23 
] #Remove
 the subscript of the array for i in range(len(list)):
     #Take out the subscript of the sequence twice for j in range(len(list)):
         #Judging the value of the subscript taken out for the first time and the value of the subscript taken out for the second time if list[ j] > list[i]:
             #If the second number is greater than the first number, put the second number after the first number 
            list[j], list[i] = list[i], list[j ]
 print (list)

    
        

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325382378&siteId=291194637