Efficient sorting algorithm: counting sort example

Counting sort is a simple and efficient sorting algorithm that is suitable for sorting integers within a certain range. Compared with the common comparison sorting algorithm, the time complexity of counting sorting is O(n+k), where n is the number of elements to be sorted and k is the range of elements to be sorted. In this article, we will explore how counting sort is implemented and provide Python code examples.

The principle of counting sort is simple: first, determine the range of elements to be sorted, and create a counting array to store the number of occurrences of each element. Then, the position of each element in the sorted array is determined by cumulative calculation. Finally, according to the information of the counting array, the elements in the array to be sorted are placed into the sorted array in order.

The following is an example of a Python implementation of counting sort:

def counting_sort(arr):
    # 确定待排序数组的最大值和最小值
    max_val = max(arr)
    min_val = min(

Guess you like

Origin blog.csdn.net/DevAstro/article/details/133498535