Common sorting methods for python lists

1. Bubble sort method

        Compare one item in the list with the next item, swapping the two positions if the previous item is greater than the next item (ascending order).

Method 1: Use the for loop directly

L=[8,2,50,3]
for i in range(len(L)):
    for j in range(i+1,len(L)):
        if L[i]>L[j]:
            L[i],L[j]=L[j],L[i]
print(L)

Method 2: Use the while statement

L=[8,2,50,3]
n=0
while n<len(L)-1:
    n+=1
    i=0
    while i<len(L)-1:
        if L[i]>L[i+1]:
            L[i],L[i+1]=L[i+1],L[i]
        i+=1
print(L)

2. Selection sort method

        Find the smallest element in the unsorted list, store it at the front of the list, then find the smallest element from the remaining elements, put it at the end of the sorted list, and so on, until all elements are sorted (ascending order)

Method 1: Use remove and append at the same time

L=[8,2,50,3]
l=[] #  创建一个空列表用于存放排序后的数据
for i in range(len(L)):
    a=min(L) #  创建一个变量存放最小值
    l.append(a) #  向空列表中加入数据
    L.remove(a) #  在原列表中将最小值剔除
print(l)

Method 2: Use pop and append at the same time

L=[8,2,50,3]

#  创建函数寻找最小元素的索引值
def Smallest(L):
  smallest = L[0]
  s = 0 #  创建变量用于存放索引值
  for i in range(1, len(L)):
    if L[i] < smallest:
      s = i 
      smallest = L[i]
  return s #  返回最小元素的列表索引值

l = [] #  创建一个空列表用以存放排序后的数据
for i in range(len(L)):
    smallest = Smallest(L)
    l.append(L.pop(smallest)) #  pop方法后跟元素当前列表最小值的索引值
print(l)

3. list.sort() method

        iterable.sort(self,key,reverse)

iterable is an iterable object, which can be a list, a collection, a dictionary

key is a function, specifying the function rules to get the elements to be sorted

Reverse implements descending sort, need to provide a bool value, the default is False (ascending)

L=[8,2,50,3]
L.sort()
print(L)

4. sorted() function

        sorted(iterable,key=None,reverse=False)

key: You can customize the sorting logic through this parameter

L=[8,2,50,3]
l=sorted(L)
print(l)

Guess you like

Origin blog.csdn.net/m0_69265664/article/details/125703164