Top ten sorting algorithms that programmers must master (Part 2)

Release: 2023-08-15 14:53:11
forward
1524 people have browsed it


#Book Issue introduction

Sort algorithmIt can be said that every programmer must have it After mastering, it is necessary to understand their principles and implementation.The following is an introduction to the Python implementation of the ten most commonly used sorting algorithms to facilitate your learning. .


01 Bubble sort-exchange sort02 Quick sort-exchange sort

03 Selection sort - selection class sorting 04 Heap sort - selection class sorting

##05 Insertion Sort - Insertion Class Sorting

06 Hill Sorting - Insertion Class Sorting

07 Merge sort - merge sort sort

##08 Counting sorting - distribution sorting

09 Radix sorting - distribution sorting

10 Bucket sorting - distribution Class sorting



##06
Hill sort
HillSort (Shell Sort): is a type of insertion sort, also known as "Diminishing Increment Sort" ), is a more efficient and improved version of the direct insertion sort algorithm.

Algorithm principle:
    Take an integer gap less than n
  • (gap is called the step size) and divide the elements to be sorted into several Group subsequence, all records whose distance is a multiple of gap are placed in the same group

  • Perform direct insertion sorting on the elements in each group, this time After the sorting is completed, the elements of each group are ordered
  • Reduce the gap value and repeat the above grouping and sorting
  • Repeat the above operation. When gap=1, the sorting ends
The code is as follows:
'''希尔排序'''
def Shell_Sort(arr):
    # 设定步长,注意类型
    step = int(len(arr) / 2)
    while step > 0:
        for i in range(step, len(arr)):
            # 类似插入排序, 当前值与指定步长之前的值比较, 符合条件则交换位置
            while i >= step and arr[i - step] > arr[i]:
                arr[i], arr[i - step] = arr[i - step], arr[i]
                i -= step
        step = int(step / 2)
    return arr

arr = [29, 63, 41, 5, 62, 66, 57, 34, 94, 22]
result = Shell_Sort(arr)
print('result list: ', result)
# result list: [5, 22, 29, 34, 41, 57, 62, 63, 66, 94]
Copy after login


#07
Merge sort
##Merge Sort : is an effective and stable sorting algorithm based on merge operations. , this algorithm is a very typical application of the divide and conquer method (Divide and Conquer), which merges ordered subsequences to obtain a completely ordered sequence.

Algorithm principle:
  • Apply for space so that its size is the sum of the two sorted sequences. This space is used to store the merged The sequence

  • sets two indexes. The initial
  • index

    positions are the starting positions of the two sorted sequences

  • Compare the elements pointed to by the two
  • indexes

    , select the relatively small element and put it into the merge space, and move the index to Next position

  • Repeat the previous step until a certain
  • index

    exceeds the end of the sequence

  • Copy all remaining elements of the other sequence directly to the end of the merged sequence
代码如下:
'''归并排序'''def Merge(left, right):
    arr = []
    i = j = 0
    while j < len(left) and  i < len(right):
        if left[j] < right[i]:
            arr.append(left[j])
            j += 1
        else:
            arr.append(right[i])
            i += 1
    if j == len(left):
        # right遍历完
        for k in right[i:]:
            arr.append(k)
    else:
        # left遍历完
        for k in left[j:]:
            arr.append(k)
    return arr

def Merge_Sort(arr):
    # 递归结束条件
    if len(arr) <= 1:
        return arr
    # 二分
    middle = len(arr) // 2
    left = Merge_Sort(arr[:middle])
    right = Merge_Sort(arr[middle:])
    # 合并
    return Merge(left, right)

arr = [27, 70, 34, 65, 9, 22, 47, 68, 21, 18]
result = Merge_Sort(arr)
print(&#39;result list: &#39;, result)
# result list: [9, 18, 21, 22, 27, 34, 47, 65, 68, 70]
Copy after login

08
计数排序
计数排序(Count sort):是一个非基于比较的排序算法,它的优势在于在对一定范围内的整数排序时,它的复杂度为Ο(n+k)(其中k是整数的范围),快于任何比较排序算法。

算法原理:
  • 找出待排序的数组中最大和最小的元素

  • 统计数组中每个值为i的元素出现的次数,存入数组C的第i项

  • 对所有的计数累加(从C中的第一个元素开始,每一项和前一项相加)

  • 反向填充目标数组:将每个元素i放在新数组的第C(i)项,每放一个元素就将C(i)减去1


代码如下:
&#39;&#39;&#39;计数排序&#39;&#39;&#39;
def Count_Sort(arr):
    max_num = max(arr)
    min_num = min(arr)
    count_num = max_num - min_num + 1
    count_arr = [0 for i in range(count_num)]
    res = [0 for i in range(len(arr))]
    # 统计数字出现的次数
    for i in arr:
        count_arr[i - min_num] += 1
    # 统计前面有几个比自己小的数
    for j in range(1, count_num):
        count_arr[j] = count_arr[j] + count_arr[j - 1]
    # 遍历重组
    for k in range(len(arr)):
        res[count_arr[arr[k] - min_num] - 1] = arr[k]
        count_arr[arr[k] - min_num] -= 1
    return res

arr = [5, 10, 76, 55, 13, 79, 5, 49, 51, 65, 30, 5]
result = Count_Sort(arr)
print(&#39;result list: &#39;, result)
# result list: [5, 5, 5, 10, 13, 30, 49, 51, 55, 65, 76, 79]
Copy after login

09
基数排序
基数排序(radix sort)是一种非比较型整数排序算法,其原理是将整数按位数切割成不同的数字,然后按每个位数分别比较。由于整数也可以表达字符串(比如名字或日期)和特定格式的浮点数,所以基数排序也不是只能使用于整数。

算法原理(以LSD为例):
  • 根据个位数的数值,遍历列表将它们分配至编号0到9的桶子中

  • 将这些桶子中的数值重新串接起来

  • 根据十位数的数值,遍历列表将它们分配至编号0到9的桶子中

  • 再将这些桶子中的数值重新串接起来


代码如下:
&#39;&#39;&#39;基数排序&#39;&#39;&#39;
def Radix_Sort(arr):
    max_num = max(arr)
    place = 0
    while 10 ** place <= max_num:
        # 创建桶
        buckets = [[] for _ in range(10)]
        # 分桶
        for item in arr:
            pos = item // 10 ** place % 10
            buckets[pos].append(item)
        j = 0
        for k in range(10):
            for num in buckets[k]:
                arr[j] = num
                j += 1
        place += 1
    return arr

arr = [31, 80, 42, 47, 35, 26, 10, 5, 51, 53]
result = Radix_Sort(arr)
print(&#39;result list: &#39;, result)
# result list: [5, 10, 26, 31, 35, 42, 47, 51, 53, 80]
Copy after login

10
桶排序
桶排序 (Bucket sort)或所谓的箱排序:划分多个范围相同的桶区间,每个桶自排序,最后合并,桶排序可以看作是计数排序的扩展。

算法原理:
  • 计算有限桶的数量

  • 逐个桶内部排序

  • 遍历每个桶,进行合并


代码如下:
&#39;&#39;&#39;桶排序&#39;&#39;&#39;
def Bucket_Sort(arr):
    num = max(arr)
    # 列表置零
    pre_lst = [0] * num
    result = []
    for data in arr:
        pre_lst[data - 1] += 1
    i = 0
    while i < len(pre_lst): # 遍历生成的列表,从小到大
        j = 0
        while j < pre_lst[i]:
            result.append(i + 1)
            j += 1
        i += 1
    return result

arr = [26, 53, 83, 86, 5, 46, 5, 72, 21, 4, 75]
result = Bucket_Sort(arr)
print(&#39;result list: &#39;, result)
# result list: [4, 5, 5, 21, 26, 46, 53, 72, 75, 83, 86]
Copy after login

The above is the detailed content of Top ten sorting algorithms that programmers must master (Part 2). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Python当打之年
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template