八大排序算法 python实现

# 直接插入排序  时间复杂度:O(n2)  稳定
def insert_sort(array):
    for i in range(len(array)):
        for j in range(i):
            if array[i] < array[j]:
                array.insert(j, array.pop(i))
                break
    return array


# 希尔排序 时间复杂度:O(n**1.3) 不稳定
def shell_sort(array):
    gap = len(array)
    while gap > 1:
        gap = gap // 2
        for i in range(gap, len(array)):
            for j in range(i % gap, i, gap):
                if array[i] < array[j]:
                    array[i], array[j] = array[j], array[i]
    return array


# 直接选择排序 时间复杂度:O(n2) 不稳定
def select_sort(array):  # 最小的数往前面放,与冒泡排序类似相反,但不稳定
    for i in range(len(array)):
        x = i  # min index
        for j in range(i, len(array)):
            if array[j] < array[x]:
                x = j
        array[i], array[x] = array[x], array[i]
    return array


# 堆排序 时间复杂度:O(nlogn) 不稳定
def heap_sort(array):
    def heap_adjust(parent):
        child = 2 * parent + 1  # left child
        while child < len(heap):
            if child + 1 < len(heap) and heap[child] < heap[child + 1]:
                child += 1  # right child
            if heap[parent] >= heap[child]:
                break
            heap[parent], heap[child] = heap[child], heap[parent]
            parent, child = child, 2 * child + 1  # 向下更新

    heap, array = array[:], []
    for i in range(len(heap) // 2 - 1, -1, -1):  # 从下向上更新大根堆
        heap_adjust(i)
    while len(heap) != 0:
        heap[0], heap[-1] = heap[-1], heap[0]
        array.insert(0, heap.pop())
        heap_adjust(0)  # 从下向上更新
    return array


# 冒泡排序 时间复杂度:O(n2),最快为n,  稳定
def bubble_sort(array):  # 最大往后面冒泡,稳定,最优情况下复杂度为O(n),其他为O(n2)
    for i in range(len(array) - 1):
        flag = False
        for j in range(len(array) - 1 - i):
            if array[j] > array[j + 1]:
                array[j], array[j + 1] = array[j + 1], array[j]
                flag = True
        if flag == False:
            return
    return array


# 快速排序 时间复杂度:O(nlogn) 不稳定
def quick_sort(array):  # 二分,时间复杂度为:nlogn,不稳定
    def recursive(begin, end):
        if begin >= end:
            return
        l, r = begin, end
        flag = array[begin]
        while l < r:
            while l < r and array[r] > flag:
                r -= 1
            while l < r and array[l] <= flag:
                l += 1
            array[l], array[r] = array[r], array[l]
        array[begin], array[l] = array[l], array[begin]
        recursive(begin, l - 1)
        recursive(r + 1, end)

    recursive(0, len(array) - 1)
    return array


# 归并排序 时间复杂度:O(nlogn) 稳定
def merge_sort(array):  # 归并排序,复杂度为:nlogn, 稳定,开辟新数组存储,原数组不变
    def merge_arr(arr_l, arr_r):
        array = []
        while len(arr_l) and len(arr_r):
            if arr_l[0] <= arr_r[0]:
                array.append(arr_l.pop(0))
            else:
                array.append(arr_r.pop(0))
        if len(arr_l) != 0:
            array += arr_l
        elif len(arr_r) != 0:
            array += arr_r
        return array

    def recursive(array):
        if len(array) == 1:
            return array
        mid = len(array) // 2
        arr_l = recursive(array[:mid])
        arr_r = recursive(array[mid:])
        return merge_arr(arr_l, arr_r)

    return recursive(array)


# 基数排序 时间复杂度:O(d(r+n)),d代表最大位数,r代表桶个数,n代表数组长度,   稳定
def radix_sort(array):
    bucket, digit = [[]], 0
    while len(bucket[0]) != len(array):
        bucket = [[], [], [], [], [], [], [], [], [], []]
        for i in range(len(array)):
            num = (array[i] // 10 ** digit) % 10  # 依次散列个位数,十位数...
            bucket[num].append(array[i])
        array.clear()
        for i in range(len(bucket)):
            array += bucket[i]
        digit += 1
    return array

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是遗传算法实现八皇后问题的Python代码: ```python import random # 棋盘大小 BOARD_SIZE = 8 # 种群大小 POPULATION_SIZE = 100 # 繁殖代数 GENERATIONS = 1000 # 交叉概率 CROSSOVER_RATE = 0.8 # 变异概率 MUTATION_RATE = 0.2 # 定义一个个体类 class Individual: def __init__(self, chromosome): self.chromosome = chromosome self.fitness = self.calculate_fitness() # 计算个体适应度 def calculate_fitness(self): clashes = 0 for i in range(len(self.chromosome)): for j in range(i + 1, len(self.chromosome)): if abs(self.chromosome[i] - self.chromosome[j]) == j - i: clashes += 1 return 1 / (clashes + 1) # 初始化种群 def init_population(): population = [] for i in range(POPULATION_SIZE): chromosome = random.sample(range(BOARD_SIZE), BOARD_SIZE) population.append(Individual(chromosome)) return population # 遗传算法 def genetic_algorithm(): # 初始化种群 population = init_population() # 进化 for generation in range(GENERATIONS): # 对种群进行排序 population = sorted(population, key=lambda x: x.fitness, reverse=True) # 输出最优解 print("Generation:", generation, "Best fitness:", population[0].fitness) # 如果找到最优解,则退出循环 if population[0].fitness == 1: break # 选择 selected_parents = selection(population) # 交叉 offspring_crossover = crossover(selected_parents) # 变异 offspring_mutation = mutation(offspring_crossover) # 更新种群 population = selected_parents + offspring_mutation # 对最终种群进行排序 population = sorted(population, key=lambda x: x.fitness, reverse=True) # 输出最优解 print("Generation:", generation + 1, "Best fitness:", population[0].fitness) print("Solution:", population[0].chromosome) # 选择 def selection(population): selected_parents = [] # 选择最优的前N个个体作为父母 for i in range(int(POPULATION_SIZE / 2)): # 选择两个随机个体 parents = random.sample(population[:int(POPULATION_SIZE / 2)], 2) # 选择适应度更高的个体作为父母 selected_parents.append(max(parents, key=lambda x: x.fitness)) return selected_parents # 交叉 def crossover(selected_parents): offspring_crossover = [] for i in range(int(POPULATION_SIZE / 2)): # 如果随机数小于交叉概率,则进行交叉 if random.random() < CROSSOVER_RATE: # 随机选择两个父母 parents = random.sample(selected_parents, 2) # 随机选择交叉点 crossover_point = random.randint(1, BOARD_SIZE - 2) # 交叉生成两个后代 offspring1 = parents[0].chromosome[:crossover_point] + parents[1].chromosome[crossover_point:] offspring2 = parents[1].chromosome[:crossover_point] + parents[0].chromosome[crossover_point:] # 将后代加入到新种群中 offspring_crossover.append(Individual(offspring1)) offspring_crossover.append(Individual(offspring2)) else: # 如果随机数大于交叉概率,则直接将父母加入到新种群中 offspring_crossover.append(selected_parents[i]) offspring_crossover.append(selected_parents[i + 1]) return offspring_crossover # 变异 def mutation(offspring_crossover): offspring_mutation = [] for i in range(len(offspring_crossover)): # 如果随机数小于变异概率,则进行变异 if random.random() < MUTATION_RATE: # 随机选择一个基因进行变异 mutation_point = random.randint(0, BOARD_SIZE - 1) # 随机生成一个新的基因 mutation_gene = random.randint(0, BOARD_SIZE - 1) # 将基因替换为新的基因 offspring_crossover[i].chromosome[mutation_point] = mutation_gene offspring_mutation.append(offspring_crossover[i]) return offspring_mutation # 运行遗传算法 genetic_algorithm() ``` 该程序使用遗传算法来解决八皇后问题。其中,个体适应度的计算方式为:将所有冲突的皇后对数加1,然后取其倒数作为适应度。种群初始化时,每个个体的染色体都是一个随机排列的数列,表示每个皇后所在的列数。在每一代的进化过程中,先对种群进行排序,然后选择适应度更高的个体作为父母进行繁殖。选择时,每次随机选择两个个体,然后选择其中适应度更高的个体作为父母。交叉时,每次随机选择两个父母,然后随机选择一个交叉点,将交叉点之前的基因从一个父母继承,交叉点之后的基因从另一个父母继承,生成两个后代。变异时,每次随机选择一个个体,然后随机选择一个基因进行变异,将其替换为一个随机生成的新基因。最后,输出最优解并结束程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值