class Solution(object):
def sortArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
"""
# 直接偷懒
return sorted(nums)
"""
"""
# 冒泡排序
def bubbleSort(nums):
for i in range(len(nums)-1,-1,-1):
for j in range(i):
if nums[j] > nums[j+1]:
nums[j],nums[j+1] = nums[j+1],nums[j]
return nums
return bubbleSort(nums)
"""
"""
# 插入排序
def insertSort(nums):
for i in range(1,len(nums)):
temp = nums[i]
index = i
while nums[index-1] > temp and index > 0:
nums[index] = nums[index-1]
index-=1
nums[index] = temp
return nums
return insertSort(nums)
"""
"""
# 选择排序
def selectSort(nums):
for i in range(len(nums)-1,1,-1):
max_index = 0
for j in range(i+1):
if nums[j] > nums[max_index]:
max_index = j
nums[max_index],nums[i] = nums[i],nums[max_index]
return nums
return selectSort(nums)
"""
"""
# 归并排序
def mergeSort(nums):
if len(nums)>1:
mid = len(nums)//2
left = nums[:mid]
right = nums[mid:]
mergeSort(left)
mergeSort(right)
i,j,k = 0, 0, 0
while i <len(left) and j <len(right):
if left[i] < right[j]:
nums[k] = left[i]
i+=1
else:
nums[k] = right[j]
j+=1
k+=1
while i < len(left):
nums[k] = left[i]
i+=1
k+=1
while j<len(right):
nums[k] = right[j]
j+=1
k+=1
return nums
return mergeSort(nums)
"""
"""
# 快速排序
def quictSort(nums):
if len(nums) < 2:
return nums
pivot = nums[len(nums)//2]
left = []
right = []
nums.remove(pivot)
for i in nums:
if i<pivot:
left.append(i)
else:
right.append(i)
return quictSort(left) + [pivot] + quictSort(right)
return quictSort(nums)
"""
"""
# 希尔排序
def shellSort(nums):
def gapInsertSort(nums,start,gap):
for i in range(start+gap,len(nums),gap):
cur = nums[i]
pos = i
while pos >= gap and nums[pos-gap] > cur:
nums[pos] = nums[pos-gap]
pos = pos - gap
nums[pos] = cur
subNumsCount = len(nums)//2
while subNumsCount > 0:
for i in range(subNumsCount):
gapInsertSort(nums,i,subNumsCount)
subNumsCount//=2
return nums
return shellSort(nums)
"""
"""
# 改善后的冒泡排序
def opt_bubbleSort(nums):
flag = True
passnum = len(nums) - 1
while passnum and flag:
flag = False
for i in range(passnum):
if nums[i] > nums[i+1]:
flag = True
nums[i],nums[i+1] = nums[i+1],nums[i]
passnum-=1
return nums
return opt_bubbleSort(nums)
"""
"""
# 不用借助额外空间的快速排序
def opt_quictSort(nums):
def partition(nums,f,l):
pivot = nums[f]
leftmark = f+1
rightmark = l
done = False
while not done:
while leftmark<=rightmark and nums[leftmark] <= pivot:
leftmark+=1
while rightmark>= pivot and leftmark<=rightmark:
rightmark+=1
if leftmark > rightmark:
done = True
else:
nums[leftmark],nums[rightmark] = nums[rightmark],numr[leftmark]
nums[f],nums[rightmark] = nums[rightmark],nums[f]
return rightmark
def quickSortHelper(nums,f,l):
if f<l:
s = partition(nums,f,l)
quickSortHelper(nums,f,s-1)
quickSortHelper(nums,s+1,l)
return nums
return quickSortHelper(nums,0,len(nums)-1)
"""
各种排序算法(python)
最新推荐文章于 2024-08-29 22:25:44 发布