关键点,找到需要交换的躺数和以及完成一趟操作后的无序区
思路:冒泡泡,按照列表顺序两两进行比较,从小到大
原列表 [3,2,1,7,4,6,8,5]
第一趟比较(i=1):[2,3,1,7,4,6,8,5]-> [2,1,3,7,4,6,8,5]-> [2,1,3,7,4,6,8,5]–>[2,1,3,4,7,6,8,5]->[2,1,3,4,6,7,8,5]->[2,1,3,4,6,7,8,5]->[2,1,3,4,6,7,5,8]。此时最大数8已经排好序,冒泡泡到了最上面的位置,此时的无序区为[2,1,3,4,6,7,5]
第二趟比较(i=2):[1,2,3,4,6,7,5]->[1,2,3,4,6,7,5]->[1,2,3,4,6,7,5]->[1,2,3,4,6,7,5]->[1,2,3,4,6,7,5]->[1,2,3,4,6,5,7]。此时第二大数7已经排好序,冒泡泡到了最上面的位置,此时的无序区为[1,2,3,4,6,5]
第三趟比较(i=3):[1,2,3,4,6,5]->[1,2,3,4,6,5]->[1,2,3,4,6,5]->[1,2,3,4,6,5]->[1,2,3,4,5,6]
def bubble(nums):
for i in range(len(nums)-1):
for j in range(len(nums)-i-1):
if nums[j] > nums[j+1]:
nums[j],nums[j+1] = nums[j+1],nums[j]
return nums
print(bubble(nums= [3,2,1,7,4,6,8,5]))
def select(nums):
for i in range(len(nums)-1):
min_loc = i
for j in range(i+1,len(nums)):
if nums[j]<nums[min_loc]:
min_loc = j
nums[i],nums[min_loc] = nums[min_loc],nums[i]
return nums
print(select(nums= [3,2,1,7,4,6,8,5]))
def insert(nums):
for i in range(1, len(nums)): # 无序区的范围
t = nums[i] # 摸到的牌
j = i-1 # 有序区的最后一个数的下标
while j >= 0 and nums[j] > t:
nums[j+1] = nums[j]
j -= 1
nums[j+1] = t
return nums
print(insert(nums= [3,2,1,7,4,6,8,5]))
def rightLocal(nums, left, right):
p = nums[left]
while left < right:
while left < right and nums[right] >= p:
right -= 1
nums[left] = nums[right]
while left < right and nums[left] <= p:
left += 1
nums[right] = nums[left]
nums[left] = p
return left
def quick_sort(nums, left, right):
if left < right:
mid = rightLocal(nums, left, right)
quick_sort(nums, left, mid-1)
quick_sort(nums, mid+1, right)
return nums
nums = [5,7,4,6,3,1,2,9,8]
print(quick_sort(nums, 0, len(nums)-1))