排序演算法總結 ING

2021-10-25 22:22:28 字數 2765 閱讀 9761

# -*- coding:utf-8 -*-

# 排序總結

# 冒泡

def maopao(nums: list) -> list:

length = nums.__len__()

for i in range(length):

for j in range(1, length):

if nums[j - 1] > nums[j]:

nums[j - 1], nums[j] = nums[j], nums[j - 1]

return nums

# 選擇

def xuanze(nums: list) -> list:

length = nums.__len__()

if length <= 1:

return nums

for i in range(length - 1):

# index_min_num:i

for j in range(i, length):

if nums[j] < nums[i]:

nums[i], nums[j] = nums[j], nums[i]

return nums

# 插入

def charu(nums: list) -> list:

length = nums.__len__()

for i in range(1, length):

need_insert_num = nums[i]

# 將nums[i]插入已排序序列nums[1..k-1]

j = i - 1

while j >= 0 and nums[j] > need_insert_num:

nums[j + 1] = nums[j]

j -= 1

nums[j + 1] = need_insert_num

return nums

# 希爾排序

def xier(nums: list) -> list:

length = nums.__len__()

gap = 1

gapc = 3

while gap < length / gapc:

gap = gap * gapc + 1

while gap > 0:

for i in range(gap, length):

temp = nums[i]

j = i - gap

while j >= 0 and nums[j] > temp:

nums[j + gap] = nums[j]

j -= gap

nums[j + gap] = temp

gap = gap // gapc

return nums

# 歸併排序

def guibing(nums: list) -> list:

def merge(left: list, right: list):

result =

while left and right:

if left[0] <= right[0]:

else:

result += left + right

return result

length = nums.__len__()

if length < 2:

return nums

middle_index = length // 2

return merge(guibing(nums[:middle_index]), guibing(nums[middle_index:]))

# 快排

def kuaipai(nums: list) -> list:

length = nums.__len__()

if length <= 1:

return nums

mid = nums[0]

left, right = ,

for i in nums[1:]:

if i <= mid:

else:

return kuaipai(left) + [mid] + kuaipai(right)

if __name__ == "__main__":

# import numpy as np

# nums = np.arange(10)

# np.random.shuffle(nums)

# nums = list(nums)

import random

nums = list(range(10))

# random.shuffle(nums)

# print(f"原始陣列: ")

import time

sorted_nums = sorted(nums)

method = [

("氣泡排序", "maopao"),

("選擇排序", "xuanze"),

("插入排序", "charu"),

("希爾排序", "xier"),

("歸併排序", "guibing"),

("快速排序", "kuaipai"),

]for i, m in enumerate(method):

random.shuffle(nums)

t0 = time.time()

assert eval(m[1])(nums) == sorted_nums

print(f": ")

分塊演算法總結(持續更新ing)

最近學了一些分塊,來總結一下個人感受 分塊是什麼呢?就是把乙個大塊拆成若干個小塊進行計算,每個小塊有可能有一些共同特點,或者每個小塊內部是有順序的,這樣,在修改操作的時候,只需要算出兩邊的節點所屬的小塊的編號分別是什麼,然後兩邊的散塊 姑且這麼叫 可以進行暴力修改,而中間的由於題目不同,可以進行不同...

面試總結 不斷ing

面試總結 2011 9 2 1 將兩個表的結果集聯合起來 答案 採用union 或者union all 區別 union all 是將結果集拼合在一起,union 是將union all 之後的結果再進行醫次distinct 去掉重複後的結果 2 有兩個表,student 學生表score 成績表,...

演算法刷題ING

給定字串j代表石頭中寶石的型別,和字串s代表你擁有的石頭。s中每個字元代表了一種你擁有的石頭的型別,你想知道你擁有的石頭中有多少是寶石。j中的字母不重複,j和s中的所有字元都是字母。字母區分大小寫,因此 a 和 a 是不同型別的石頭。示例 輸入 j aa s aaabbbb 輸出 3class so...