排序算法
- 简单选择排序
思路:从列表中,找到最小的值的下标,记录最小值的位置,与第一位互换;在从剩下列表中,找出最小值的下标,与第二位互换;…
nums = [7,5,4,3,1,2,6,9,8,0]
print(nums)
for i in range(len(nums)):
min_value = nums[i]
min_index = 0
for j in range(1,len(nums)):
if nums[j] < min_value:
min_value = nums[j]
min_value = j
nums[i], nums[min_value] = nums[min_value], nums[i]
print(nums)
- 冒泡排序
思路:相邻两个元素进行比较,如果第一个大于第二,两个元素交换… 第一轮交换下来最大值就在最右边
nums = [7,5,4,3,1,2,6,9,8,0]
print(nums)
for i in range(len(nums)-1):
for j in range(len(nums)):
if nums[j] > nums[j+1]:
nums[j+1], nums[j+1] = nums[j+1], nums[j]
print(nums)
2.1 冒泡排序的改良
nums = [10,9,1,2,3,4,5,6,7,8]
print(nums)
for i in range(len(nums)-1):
is_prime = True
for j in range(len(nums)-i - 1):
if nums[j] > nums[j+1]:
nums[j+1], nums[j] = nums[j], nums[j+1]
is_prime = False
if is_prime:
break
print(nums)
2.2 鸡尾酒排序 思路:正向比较后,在反向比较一次;依次进行
nums = [9,1, 2, 3, 4, 5, 6, 7, 8,0]
print(nums)
for i in range(len(nums)-1):
is_prime = True
for j in range(len(nums)-i - 1):
if nums[j] > nums[j+1]:
nums[j+1], nums[j] = nums[j], nums[j+1]
is_prime = False
for j in range(len(nums),0,-1):
if nums[j] < nums[j-1]:
nums[j-1], nums[j] = nums[j], nums[j-1]
is_prime = False
if is_prime:
break
print(nums)
练习
3.1. 幸运的女人(josephu环) 15人男人,15个女人一起出海,船坏了,需要把其中15个人扔到海里;所有人围成一圈,由某个人从1开始依次报数,报到9的人被扔到海里,下一个重新从1开始报数,问开始那些位置是男人,那些位置是女人 思路:从1数到9,数到9时,又重新开始数,一共需要数15次9;当下次数到9时,跳过此元素。
persons = [1]*30
count, number,index= 0,0,0
while count < 15:
if persons[index]:
number += 1
if number == 9:
persons[index] = 0
count += 1
number = 0
index += 1
if index == 30:
index = 0
print(persons)
3.2第二种解法 遇到9就删除元素,删除下标为8的元素
persons = [i for i in range(1,31)]
number = 8
for i in range(15):
persons.pop(number)
number = (number+8) % len(persons)
print(persons)
|