Sorting Algorithm of Blue Bridge Cup Algorithm

Tip: This series of blogs is a summary of the python notes of the bilibili algorithm course "The Algorithm is Beautiful", which absorbs the original blogs of many excellent bloggers. Since I did not attach the corresponding blog address to the summary, if you find that the content of this blog is not related to yours The content of the blog matches, please contact the author and add a reference address for you.
bilibili course address


foreword

排序算法虽然已经内置在python函数,但其排序原理的学习对算法入门帮助良多

Simple sorting algorithms can be divided into bubble sorting, selection sorting, insertion sorting and Hill sorting. The following is an introduction and code display of bubble sorting and selection sorting in the sorting algorithm. Code compilation environment: python 3.8.6


1. Bubble sort

1) Principle introduction

The time complexity of bubble sorting is O[n*n], which is the simplest and most violent sorting method. Its working principle is to compare two pairs each time, and put the larger value behind at one time, and finally complete the ascending sort.

N number n-1 times of bubbling
Principle: Each time the inner loop sorts, the front and rear two elements in the list are exchanged, showing a trend of moving the large element backward. Every time the outer loop sorts, the largest element is moved to the last position and fixed by the inner loop.

2) Code example

#冒泡排序优化版,避免已经排好的序列重排的问题
def bubble_sort1(nums):
    for i in range(len(nums) - 1):  
        flag = False  # 改进后的冒泡,设置一个flag作为一个标志位
        for j in range(len(nums) - i - 1):   
            if nums[j] > nums[j + 1]:
                nums[j], nums[j + 1] = nums[j + 1], nums[j]
                flag = True
        if not flag:
            return nums  #对排好的序列,提前终止

    return nums  # 整个数据全部运行完排好的序列
#a=[2,5,3,4,56,32,45,7]
#bubble_sort1(a)
#print(a)

2. Selection sort

1) Principle introduction

Its complexity is still O(n*n), but its performance is slightly better than that of bubbling. Its sorting principle is to place the minimum value in the current position every time it traverses.

Principle: Every sorting finds the minimum value and puts it in the first place and fixes it

2) Code example

lists=list(map(int,input().split()))
def choice_sort(lists):
    for i in range(len(lists)):
        for j in range(i,len(lists)):
            if lists[i]>lists[j]:
                lists[i],lists[j]=lists[j],lists[i]
    return lists
#print(choice_sort(lists))

Summarize

This article introduces the bubble sorting, selection sorting and codes in the sorting algorithm. It is recommended that readers use it in conjunction with the video teaching content. The next blog is an introduction to insertion sorting and Hill sorting. (The author has brand new learning materials for the Blue Bridge Cup, including but not limited to some fee-paying courses, please private if interested)

Guess you like

Origin blog.csdn.net/qq_44840741/article/details/124066169