Python排序部分

This commit is contained in:
NIngCoder 2022-11-25 15:47:05 +08:00
parent 83629f3d2c
commit 121cb10209
4 changed files with 102 additions and 0 deletions

View file

@ -8,3 +8,30 @@ import sys, os.path as osp
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from include import *
"冒泡排序"
def bubble_sort(nums):
n=len(nums)
# 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i in range(n-1,-1,-1):
# 内循环:冒泡操作
for j in range(i):
if nums[j]>nums[j+1]:
nums[j],nums[j+1]=nums[j+1],nums[j]
"冒泡排序(标志优化)"
def bubbleSortWithFlag(nums):
n=len(nums)
# 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i in range(n-1,-1,-1):
flag=False #初始化标志位
# 内循环:冒泡操作
for j in range(i):
if nums[j]>nums[j+1]:
nums[j],nums[j+1]=nums[j+1],nums[j]
flag=True #记录交换元素
if not flag:break
if __name__=='__main__':
nums=[4,1,3,1,5,2]
bubble_sort(nums)
print("冒泡排序后数组 nums = " ,nums)
bubbleSortWithFlag(nums)
print("冒泡排序后数组 nums = " ,nums)

View file

@ -8,3 +8,19 @@ import sys, os.path as osp
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from include import *
"直接插入排序"
def insertionSort(nums):
#外循环base = nums[1], nums[2], ..., nums[n-1]
for i in range(1,len(nums)):
base=nums[i]
j=i-1
#内循环:将 base 插入到左边的正确位置
while j>=0 and nums[j]>base:
nums[j+1]=nums[j] #1. 将 nums[j] 向右移动一位
j-=1
nums[j+1]=base #2. 将 base 赋值到正确位置
if __name__=='__main__':
nums=[4,1,3,1,5,2]
insertionSort(nums)
print("排序后数组 nums = " ,nums)

View file

@ -8,3 +8,41 @@ import sys, os.path as osp
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from include import *
"""
另一种 思路实现归并排序
"""
def merge_sort(nums,l,r):
if l>=r:return
mid=l+r>>1 #划分中点
#进行归并
merge_sort(nums,l,mid)
merge_sort(nums,mid+1,r)
k,i,j=0,l,mid+1 #借助辅助数组 完成排序
while i<=mid and j<=r:
if nums[i]<=nums[j]: #这一步保证了 稳定排序
help_ls[k]=nums[i]
i+=1
else:
help_ls[k]=nums[j]
j+=1
k+=1
while i<=mid: #对于左边区域
help_ls[k]=nums[i]
k,i=k+1,i+1
while j<=r: #对于右边区域
help_ls[k]=nums[j]
k,j=k+1,j+1
i,j=l,0
while i<=r:
nums[i]=help_ls[j]
i,j=i+1,j+1
if __name__=='__main__':
nums=[4,1,3,1,5,2]
n=len(nums)
help_ls=[0 for _ in range(n)]
merge_sort(nums,0,n-1)
print("归并排序完成后 nums = ",nums)

View file

@ -8,3 +8,24 @@ import sys, os.path as osp
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from include import *
"另一种思维 实现快速排序"
def quick_sort(nums,l,r):
if l>=r:
return
i,j,x=l-1,r+1,nums[l+r>>1]
while i<j:
while True:
i+=1
if nums[i]>=x:break
while True:
j-=1
if nums[j]<=x:break
if i<j:nums[i],nums[j]=nums[j],nums[i]
quick_sort(nums,l,j),quick_sort(nums,j+1,r)
if __name__=='__main__':
nums=[4,1,3,1,5,2]
n=len(nums)
help_ls=[0 for _ in range(n)]
quick_sort(nums,0,n-1)
print("快速排序完成后 nums = ",nums)