1.题目,给你一个列表【100,96,98,90】,输出从大到小排列的位次。要求排序不用库函数。
#coding=utf-8
import sys
def newsort(list1):
i = 1
listd = {}
for listvalue in list1:
listd[listvalue] = i
i = i + 1
listad = sortpop(list1)
for ite4m in listad:
print(listd[ite4m])
def sortpop(listd):
"""对元素排序"""
n = len(listd)
for j in range(0, n -1 ):
for i in range(0, n - 1 -j):
if listd[i] > listd[i + 1]:
temp = listd[i]
listd[i] = listd[i + 1]
listd[i + 1] = temp
return listd
newsort([100,63,98,97])
2.python分治法实现快速排序:
整体思路:(1)一个指针指右,一个指针指左
(2)左边第一个数当标杆
(3)当左小与右:
当左指针小于右指针,并且右指针所指比key大: 右指针左移
否则:左小与右时:右赋值给左,左加一
当左小与右,并且左指针所指小于K:左指针右移。
否则:左小与右时:左赋值给右,右加一
否则循环结束,key赋值给left, 返回左。
注意:每一步判断或者while,都要判断左小与右。自己不注意,出错了很多次
def partition(listd, low, high):
"""对元素排序"""
left = low
right = high
k = listd[low]
while left < right:
while listd[right] > k and left < right:
right = right - 1
if left < right:
listd[left] = listd[right]
left = left + 1
while listd[left] < k and left < right:
left = left + 1
if left < right:
listd[right] = listd[left]
right = right - 1
listd[left] = k
return left
def quicksort(listd, low, hight):
if low < hight:
k = partition(listd, low, hight)
quicksort(listd, low, k-1)
quicksort(listd, k + 1, hight)
list1 = [100, 97, 96, 97, 30]
quicksort(list1, 0, 4)
print(list1)