Python implementation classical sorting algorithm

stability:

Stable sorting algorithms: bubble sort, insertion sort, merge sort and radix sort.

Not a stable sorting algorithms: selection sort, quick sort, shell sort, heap sort.

This article describes the selection and bubble sort.

Bubble Sort:

  • Compare adjacent elements. If the first is greater than the second, the two of them exchanged.

  • Do the same work for each pair of adjacent elements, from the beginning to the end of the first to the last pair. Once this is done, the last element is the biggest number.

  • Repeat these steps for all elements, except the last one.

  • Continued to repeat the above steps for each time fewer and fewer elements, until there is no need to compare a pair of numbers

a=[80,15,45,35,88,46,55,66,22,99,0,-1,-100]
for j in range(0,len(a)):
    for i in range(0,len(a)-1):
        if a[i]>a[i+1]:
            a[i], a[i + 1] = a[i + 1], a[i]
print(a)

Selection Sort

  • First, find the smallest sequence of unsorted (large) element, the starting position is stored in the sorted sequence

  • From the remaining unsorted then continue to look for the minimum element (large) element, and then into the end of the sorted sequence.

  • The second step is repeated until all the elements are sorted completed.

a=[80,15,45,35,88,46,55,66,22,99,0,-1,-100]
for i in range(len(a),0,-1): //在这里选择排序选择最大的数,进行比较
    max=0
    for j in range(1,i):
        if a[j]>a[max]:
            max=j
    a[max],a[i-1]=a[i-1],a[max]
print(a)

At last! !

Py comes with sorting function! ! ! !

  • sort()
a=[80,15,45,35,88,46,55,66,22,99,0,-1,-100]
a.sort(reverse=True)//reverse=True倒序排序
print(a)
  • sorted()
users = [{'name':'jack', 'age':26}, {'name':'cindy', 'age':19}]
sorted(users, key=lambda x:x['age'])

//key=lambda x:x['age'] 根据“age”属性进行排序

[{'name': 'cindy', 'age': 19}, {'name': 'jack', 'age': 26}]

                                      Very convenient

Released two original articles · won praise 1 · views 270

Guess you like

Origin blog.csdn.net/qq_41969523/article/details/104870035