以下是用 Python 编写的选择排序算法:

def selection_sort(arr):
    # 遍历数组
    for i in range(len(arr)):
        # 找到未排序部分的最小元素的索引
        min_index = i
        for j in range(i+1, len(arr)):
            if arr[j] < arr[min_index]:
                min_index = j
        # 将最小元素与当前位置交换
        arr[i], arr[min_index] = arr[min_index], arr[i]
    
    return arr

# 测试排序算法
arr = [64, 25, 12, 22, 11]
sorted_arr = selection_sort(arr)
print("排序后的数组:", sorted_arr)

输出:

排序后的数组: [11, 12, 22, 25, 64]

这个选择排序算法的时间复杂度是 O(n^2),其中 n 是数组的长度。

Python 选择排序算法实现及详解

原文地址: https://www.cveoy.top/t/topic/pSmi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录