网络编程
位置:首页>> 网络编程>> Python编程>> Python实现排序方法常见的四种

Python实现排序方法常见的四种

作者:小小程序员ol  发布时间:2022-02-18 08:06:15 

标签:python,排序方法

1.冒泡排序,相邻位置比较大小,将比较大的(或小的)交换位置


def maopao(a):
   for i in range(0,len(a)):
       for j in range(0,len(a)-i-1):
           if a[j]>a[j+1]:
               temp = a[j+1]
               a[j+1] = a[j]
               a[j] = temp
               #print(a)
       #print(a)
   print(a)

2.选择排序,遍历选择一个最小的数与当前循环的第一个数交换


def xuanze(a):
   for i in range(0,len(a)):
       k=i
       temp = a[i]
       for j in range(i,len(a)):
           if a[j]<temp:
               temp = a[j]
               k = j
       a[k] = a[i]
       a[i] = temp
   print(a)

3.快速排序:将子段的第一个元素做为中值,先从右向左遍历,如过比中值大high-1,如果比中值小,将这个值放到low那里。

然后从左向右开始遍历,如果左侧的比中值大,将他放到high那里。当low>=high时,将中值的值赋给low

(1.以下为参照公众号中的做法:


a =[7,1,3,2,6,54,4,4,5,8,12,34]
def sort(a,low,high):
   while low < high:
       temp = a[low]
       while low < high and a[high]>=temp:
           high = high-1
       a[low]=a[high]
       while low<high and a[low]<temp:
           low = low+1
       a[high]=a[low]          
       a[low]=temp
   return low
def quicksort(a,low,high):
   if low<high:
       middle = sort(a,low,high)
       quicksort(a,low,middle)
       quicksort(a,middle+1,high)
       print(a)
sort(a,0,len(a)-1)
quicksort(a,0,len(a)-1)
print(a)

(2.以下是参照网上的做法:

在做快速排序时一直各种问题,是因为地柜那里没有考虑清楚,一直把low的值赋值为0了,实际上应该是不固定的low值,他每个子循环不定。


'''
遇到问题没人解答?小编创建了一个Python学习交流群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
a =[7,1,3,2,6,54,4,4,5,8,12,34]
def sort(a,low,high):
   while low < high:
       temp = a[low]
       while low < high and a[high]>=temp:
           high = high-1
       while low<high and a[high]<temp:
           a[low]=a[high]          
           low =low+1
           a[high]=a[low]
       a[low]=temp
   return low
def quicksort(a,low,high):
   if low<high:
       middle = sort(a,low,high)
       quicksort(a,low,middle)
       quicksort(a,middle+1,high)
       print(a)
sort(a,0,len(a)-1)
quicksort(a,0,len(a)-1)
print(a)

4.插入排序:从左向右遍历,依次选取数值,从数值的左侧从右向左遍历,选择第一个比他小的数值的右侧插入该数值,其他数值依次向后赋值


#插入排序
a =[7,1,3,2,6,54,4,4,5,8,12,34]
for i in range(0,len(a)-1):
   temp=a[i+1]
   j=i+1
   while j>=0 and temp<a[j-1]:
       j=j-1      
       print(j)
   if j>=-1:
       k= i+1
       while k>=j:
           a[k]=a[k-1]
           k=k-1
           print(a)
       a[j]=temp
print(a)

插入排序方法2,用到了列表的a.insert(1,2)和清楚a[2:3]=[],这样可以少用一个循环


a =[7,1,3,2,6,54,4,4,5,8,12,34]
for i in range(1,len(a)-1):
   temp=a[i]

j=i-1
   while j>=0 and temp<=a[j]:
       print(temp)
       j=j-1
   if j >=-1:
       a[i:i+1]=[]
       a.insert(j+1,temp)
       print(a)
print(a)

来源:https://www.cnblogs.com/python960410445/p/15013047.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com