Sort method --python

1, bubble sort (Bubble Sort)

  • Compare adjacent elements. If the first is larger than a second, to exchange their two;
  • We do the same work for each pair of adjacent elements, from the beginning to the end of the first to the last pair, so that should be the last element is the largest number;
  • Repeating the above steps for all elements, except the last one;
  • Repeat steps 1 to 3 until the sorting is completed.

def BubbleSort(lst):
    n=len(lst)
    if n<=1:
        return lst
    for i in range (0,n):
        for j in range(0,n-i-1):
            if lst[j]>lst[j+1]:
                (lst[j],lst[j+1])=(lst[j+1],lst[j])
    return lst

2, quick sort (Quick Sort)

  • Pick one element from the series, referred to as a "reference" (Pivot);
  • Reorder columns, all the elements are placed in front of the small base than the reference value, all the elements placed behind the baseline larger than the reference value (the same number can be either side). After the partition exit, on the basis of the number of columns in the middle position. This is called a partition (Partition) operation;
  • Number of sub recursively (recursive This) than the reference value the number of columns and the sub-element is greater than the reference value of the element column.

DEF the QuickSort (LST):
     # This is the function partitioning 
    DEF Partition (ARR, left, right): 
        Key = left   # divides the reference index number, the first number is a default number of reference, you can optimize 
        the while left < right:
             # If number list behind, larger than the reference number or equal, then move up by one until there is less than the reference number of the number of appearances of 
            the while left <right and arr [right]> = arr [Key]: 
                right - = 1
             # If the front of the list number, equal to or smaller than the reference number, the backward until a number larger than the reference number of appearances of 
            the while left <right and ARR [left] <= ARR [Key]: 
                left + =. 1
             # at this time to find a larger than the reference book, and a smaller number than the benchmark, they will switch places
            (arr [left], ARR [right]) = (ARR [right], ARR [left]) 
 
        # When approaching from both sides, respectively, until the end position is equal to two, the left side with a small reference exchange 
        (arr [left ], arr [Key]) = (arr [Key], left arr [])
         # returns the current position of the reference where the index 
        return left 
 
    DEF quicksort (arr, left, right):  
         IF left> = right:
             return 
        # from the baseline start partition 
        MID = partition (ARR, left, right)
         # recursive call 
        # Print (ARR) 
        quicksort (ARR, left, MID -. 1 ) 
        quicksort (ARR, MID +. 1 , right) 
 
    # main function 
    n = len(lst)
    if n <= 1:
        return lst
    quicksort(lst, 0, n - 1)
    return lst

3, insertion sort (Insert Sort)

  • Starting with the first element, which can be considered to have been sorted;
  • Remove the next element from the forward scan has been sorted in the sequence of elements;
  • If the element (sorted) is greater than the new element, the element to the next position;
  • Repeat step 3 until it finds the sorted elements less than or equal to the new position of the element;
  • After the new element is inserted into this position;
  • Repeat steps 2-5.

def InsertSort(lst):
    n=len(lst)
    if n<=1:
        return lst
    for i in range(1,n):
        j=i
        target=lst[i]            #每次循环的一个待插入的数
        while j>0 and target<lst[j-1]:       #比较、后移,给target腾位置
            lst[j]=lst[j-1]
            j=j-1
        lst[j]=target            #把target插到空位
    return lst

4、希尔排序法(Shell Sort)

  • 选择一个增量序列t1,t2,…,tk,其中ti>tj,tk=1;
  • 按增量序列个数k,对序列进行k 趟排序;
  • 每趟排序,根据对应的增量ti,将待排序列分割成若干长度为m 的子序列,分别对各子表进行直接插入排序。仅增量因子为1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。

def ShellSort(lst):
    def shellinsert(arr,d):
        n=len(arr)
        for i in range(d,n):
            j=i-d
            temp=arr[i]             #记录要出入的数
            while(j>=0 and arr[j]>temp):    #从后向前,找打比其小的数的位置
                arr[j+d]=arr[j]                 #向后挪动
                j-=d
            if j!=i-d:
                arr[j+d]=temp
    n=len(lst)
    if n<=1:
        return lst
    d=n//2
    while d>=1:
        shellinsert(lst,d)
        d=d//2
    return lst

 5、选择排序法(Select Sort)

  • 初始状态:无序区为R[1..n],有序区为空;
  • 第i趟排序(i=1,2,3…n-1)开始时,当前有序区和无序区分别为R[1..i-1]和R(i..n)。该趟排序从当前无序区中-选出关键字最小的记录 R[k],将它与无序区的第1个记录R交换,使R[1..i]和R[i+1..n)分别变为记录个数增加1个的新有序区和记录个数减少1个的新无序区;
  • n-1趟结束,数组有序化了。

def SelectSort(lst):
    n = len(lst)
    if n<=1:
        return lst
    for i in range(0,n-1):
        minIndex = i
        for j in range(i+1,n): #比较一遍,记录索引不交换
            if lst[j]<lst[minIndex]:
                minIndex=j
        if minIndex!=i:
            (lst[minIndex],lst[i])=(lst[i],lst[minIndex])
    return lst

 6、堆积排序法(Heap Sort)

  • 将初始待排序关键字序列(R1,R2….Rn)构建成大顶堆,此堆为初始的无序区;
  • 将堆顶元素R[1]与最后一个元素R[n]交换,此时得到新的无序区(R1,R2,……Rn-1)和新的有序区(Rn),且满足R[1,2…n-1]<=R[n];
  • 由于交换后新的堆顶R[1]可能违反堆的性质,因此需要对当前无序区(R1,R2,……Rn-1)调整为新堆,然后再次将R[1]与无序区最后一个元素交换,得到新的无序区(R1,R2….Rn-2)和新的有序区(Rn-1,Rn)。不断重复此过程直到有序区的元素个数为n-1,则整个排序过程完成

def  HeapSort(lst):
    def heapadjust(arr,start,end):  #将以start为根节点的堆调整为大顶堆
        temp=arr[start]
        son=2*start+1
        while son<=end:
            if son<end and arr[son]<arr[son+1]:  #找出左右孩子节点较大的
                son+=1
            if temp>=arr[son]:       #判断是否为大顶堆
                break
            arr[start]=arr[son]     #子节点上移
            start=son                     #继续向下比较
            son=2*son+1
        arr[start]=temp             #将原堆顶插入正确位置
#######
    n=len(lst)
    if n<=1:
        return lst
    #建立大顶堆
    root=n//2-1    #最后一个非叶节点(完全二叉树中)
    while(root>=0):
        heapadjust(lst,root,n-1)
        root-=1
    #掐掉堆顶后调整堆
    i=n-1
    while(i>=0):
        (lst[0],lst[i])=(lst[i],lst[0])  #将大顶堆堆顶数放到最后
        heapadjust(lst,0,i-1)    #调整剩余数组成的堆
        i-=1
    return lst

7、归并排序法(Merge Sort)

  • 把长度为n的输入序列分成两个长度为n/2的子序列;
  • 对这两个子序列分别采用归并排序;
  • 将两个排序好的子序列合并成一个最终的排序序列

def MergeSort(lst):
    #合并左右子序列函数
    def merge(arr,left,mid,right):
        temp=[]     #中间数组
        i=left          #左段子序列起始
        j=mid+1   #右段子序列起始
        while i<=mid and j<=right:
            if arr[i]<=arr[j]:
                temp.append(arr[i])
                i+=1
            else:
                temp.append(arr[j])
                j+=1
        while i<=mid:
            temp.append(arr[i])
            i+=1
        while j<=right:
            temp.append(arr[j])
            j+=1
        for i in range(left,right+1):    #  !注意这里,不能直接arr=temp,他俩大小都不一定一样
            arr[i]=temp[i-left]
    #递归调用归并排序
    def mSort(arr,left,right):
        if left>=right:
            return
        mid=(left+right)//2
        mSort(arr,left,mid)
        mSort(arr,mid+1,right)
        merge(arr,left,mid,right)
 
    n=len(lst)
    if n<=1:
        return lst
    mSort(lst,0,n-1)
    return lst

8、基数排序法(Radix Sort)

  • 取得数组中的最大数,并取得位数;
  • arr为原始数组,从最低位开始取每个位组成radix数组;
  • 对radix进行计数排序(利用计数排序适用于小范围数的特点);

import math
def RadixSort(lst):
    def getbit(x,i):       #返回x的第i位(从右向左,个位为0)数值
        y=x//pow(10,i)
        z=y%10
        return z
    def CountSort(lst):
        n=len(lst)
        num=max(lst)
        count=[0]*(num+1)
        for i in range(0,n):
            count[lst[i]]+=1
        arr=[]
        for i in range(0,num+1):
            for j in range(0,count[i]):
                arr.append(i)
        return arr
    Max=max(lst)
    for k in range(0,int(math.log10(Max))+1):             #对k位数排k次,每次按某一位来排
        arr=[[] for i in range(0,10)]
        for i in lst:                 #将ls(待排数列)中每个数按某一位分类(0-9共10类)存到arr[][]二维数组(列表)中
            arr[getbit(i,k)].append(i)
        for i in range(0,10):         #对arr[]中每一类(一个列表)  按计数排序排好
            if len(arr[i])>0:
                arr[i]=CountSort(arr[i])
        j=9
        n=len(lst)
        for i in range(0,n):     #顺序输出arr[][]中数到ls中,即按第k位排好
            while len(arr[j])==0:
                j-=1
            else:
                lst[n-1-i]=arr[j].pop()   
    return lst    

转载链接:https://blog.csdn.net/weixin_41571493/article/details/81875088

 

Guess you like

Origin www.cnblogs.com/fighting25/p/11271353.html