首页 > 编程语言 >python: Ten Sort Algotrthms

python: Ten Sort Algotrthms

时间:2023-07-05 22:56:06浏览次数:38  
标签:Sort arr return python items self param range Algotrthms

 

# encoding: utf-8
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 11
# Datetime  : 2023/7/2 20:25
# User      : geovindu
# Product   : PyCharm
# Project   : pythonStudyDemo
# File      : TenSortAlgotrthms.py
# explain   : 学习 十种排序  https://www.sitepoint.com/best-sorting-algorithms/  python javascript

from enum import Enum
import sortingalgorithms.CheckSort
import sortingalgorithms.duplicateChecking
from heapq import heappop, heappush

class TenSortAlgotrthms(object):
    """

    """
    def bubbleSort(self,arr):
        """
        1。冒泡排序方法bubble Sort   从小至大 升序
        :param arr 整数数组  如 arr = [64, 34, 25, 12, 22, 11, 90]
        :return:
        """
        n = len(arr)
        swapped = False
        for i in range(n - 1):
            for j in range(0, n - i - 1):
                 if arr[j] > arr[j + 1]:
                    swapped = True
                    arr[j], arr[j + 1] = arr[j + 1], arr[j]

            if not swapped:
               return

    def bubbleSort(self,arr,checkSort=None):
        """
        1。冒泡排序方法  从小至大 升序
        :param arr 整数数组  如 arr = [64, 34, 25, 12, 22, 11, 90]
        :param checkSort选择排序方式 Desc 降序 Asc 升序
        :return:
        """
        n = len(arr)

        swapped = False
        if(checkSort!=None):
            if(checkSort.Asc==sortingalgorithms.CheckSort.CheckSort.Desc):
                for i in range(n - 1):
                    for j in range(0, n - i - 1):
                        if arr[j] > arr[j + 1]:
                            swapped = True
                            arr[j], arr[j + 1] = arr[j + 1], arr[j]

                    if not swapped:
                        return

            else:
                for i in range(n - 1):
                    for j in range(0, n - i - 1):
                        if arr[j] < arr[j + 1]:
                            swapped = True
                            arr[j], arr[j + 1] = arr[j + 1], arr[j]

                    if not swapped:
                        return
        else:
            for i in range(n - 1):
                for j in range(0, n - i - 1):
                    if arr[j] > arr[j + 1]:
                        swapped = True
                        arr[j], arr[j + 1] = arr[j + 1], arr[j]

                if not swapped:
                    return



    def bubbleSortIndex(self, arr, checkSort, eqLeter : int):
        """
        1。冒泡排序方法 bubble Sort  从小至大 升序
        :param arr 整数数组  如 arr = [64, 34, 25, 12, 22, 11, 90]
        :param checkSort选择排序方式 Desc 降序 Asc 升序
        :param eqLeter 找查指定的数字的下标
        :return:返回下标 元组
        """
        n = len(arr)
        fin = sortingalgorithms.duplicateChecking.DuplicateChecking()
        index = fin.findindex(arr, eqLeter)
        # print("index" ,index ,eqLeter)
        swapped = False
        if(checkSort.Asc == sortingalgorithms.CheckSort.CheckSort.Desc):
            for i in range(n - 1):
                for j in range(0, n - i - 1):
                    if arr[j] > arr[j + 1]:
                        swapped = True
                        arr[j], arr[j + 1] = arr[j + 1], arr[j]

                if not swapped:
                    return index


        else:
            for i in range(n - 1):
                for j in range(0, n - i - 1):
                    if arr[j] < arr[j + 1]:
                        swapped = True
                        arr[j], arr[j + 1] = arr[j + 1], arr[j]

                if not swapped:
                    return index

    def insertionSort(self,items:list):
        """
        2 插入排序(Insertion Sort) items = [6,20,8,19,56,23,87,41,49,53]
        print(insertionSort(items))
        :param items
        :return:
        """
        for i in range(1, len(items)):
            j = i
            while j > 0 and items[j-1] > items[j]:
                items[j-1], items[j] = items[j], items[j-1]
                j -= 1
        return items

    def quickSort(self,items:list):
        """
        3 快速排序(Quick Sort) quick Sort  items = [6,20,8,19,56,23,87,41,49,53]
        print(quickSort(items))
        :param items
        :return:
        """
        if len(items) > 1:
            pivot = items[0]
            left = [i for i in items[1:] if i < pivot]
            right = [i for i in items[1:] if i >= pivot]
            return self.quickSort(left) + [pivot] + self.quickSort(right)
        else:
            return items

    def bucketSort(self,items:list):
        """
        4 桶排序(Bucket Sort) Bucket sort items = [6,20,8,19,56,23,87,41,49,53]
        print(bucketSort(items))
        :param items:
        :return:
        """
        buckets = [[] for _ in range(len(items))]
        for item in items:
            bucket = int(item/len(items))
            buckets[bucket].append(item)
        for bucket in buckets:
            bucket.sort()
        return [item for bucket in buckets for item in bucket]


    def shellSort(self,items:list):
        """
        5 希尔排序(Shell Sort)items = [6,20,8,19,56,23,87,41,49,53]
        print(shellSort(items))
        :param items:
        :return:
        """
        sublistcount = len(items)//2
        while sublistcount > 0:
            for start in range(sublistcount):
                self.gap_insertion_sort(items, start, sublistcount)
            sublistcount = sublistcount // 2
        return items

    def gap_insertion_sort(self,items:list, start, gap):
        """

        :param items:
        :param start:
        :param gap:
        :return:
        """
        for i in range(start+gap, len(items), gap):
            currentvalue = items[i]
            position = i
            while position >= gap and items[position-gap] > currentvalue:
                items[position] = items[position-gap]
                position = position-gap
            items[position] = currentvalue

    def mergeSort(self,items:list):
        """
         6.归并排序(Merge Sort)items = [6,20,8,19,56,23,87,41,49,53]
            print(mergeSort(items))

        :param items:
        :return:
        """
        if len(items) <= 1:
            return items

        mid = len(items) // 2
        left = items[:mid]
        right = items[mid:]

        left = self.mergeSort(left)
        right = self.mergeSort(right)

        return self.merge(left, right)

    def merge(self,left, right):
        """

        :param left:
        :param right:
        :return:
        """
        merged = []
        left_index = 0
        right_index = 0

        while left_index < len(left) and right_index < len(right):
            if left[left_index] > right[right_index]:
                merged.append(right[right_index])
                right_index += 1
            else:
                merged.append(left[left_index])
                left_index += 1

        merged += left[left_index:]
        merged += right[right_index:]

        return merged

    def selectionSort(self,items:list):
        """
        7 选择排序(Selection Sort)items = [6,20,8,19,56,23,87,41,49,53]
        print(selectionSort(items))
        :param items:
        :return:
        """
        for i in range(len(items)):
            min_idx = i
            for j in range(i + 1, len(items)):
                if items[min_idx] > items[j]:
                    min_idx = j
            items[i], items[min_idx] = items[min_idx], items[i]
        return items

    def radixSort(self,items:list):
        """

        8 基数排序(Radix Sort)items = [6,20,8,19,56,23,87,41,49,53]
        print(radixSort(items))
        :param items:
        :return:
        """
        max_length = False
        tmp, placement = -1, 1

        while not max_length:
            max_length = True
            buckets = [list() for _ in range(10)]

            for i in items:
                tmp = i // placement
                buckets[tmp % 10].append(i)
                if max_length and tmp > 0:
                    max_length = False

            a = 0
            for b in range(10):
                buck = buckets[b]
                for i in buck:
                    items[a] = i
                    a += 1

            placement *= 10
        return items

    def combSort(self,items:list):
        """
        9 梳排序(Comb sort)(梳排序是一种不稳定排序算法,改良自泡沫排序和快速排序。其目的是消除阵列尾部的小数值,提高排序效率)
        :param items:
        :return:
        """
        gap = len(items)
        shrink = 1.3
        sorted = False
        while not sorted:
            gap //= shrink
            if gap <= 1:
                sorted = True
            else:
                for i in range(len(items) - gap):
                    if items[i] > items[i + gap]:
                        items[i], items[i + gap] = items[i + gap], items[i]
        return self.bubble_sort(items)

    def bubble_sort(self,items:list):
        """

        :param items:
        :return:
        """
        for i in range(len(items)):
            for j in range(len(items) - 1 - i):
                if items[j] > items[j + 1]:
                    items[j], items[j + 1] = items[j + 1], items[j]
        return items

    def insertionSort(self,arr, left=0, right=None):
        """

        :param arr:
        :param left:
        :param right:
        :return:
        """
        if right is None:
            right = len(arr) - 1

        for i in range(left + 1, right + 1):
            key_item = arr[i]
            j = i - 1
            while j >= left and arr[j] > key_item:
                arr[j + 1] = arr[j]
                j -= 1
            arr[j + 1] = key_item

        return arr

    def merge(self,left, right):
        """

        :param left:
        :param right:
        :return:
        """
        if not left:
            return right

        if not right:
            return left

        if left[0] < right[0]:
            return [left[0]] + self.imerge(left[1:], right)

        return [right[0]] + self.imerge(left, right[1:])

    def timSort(self,arr):
        """
        10 TimSort是结合了合并排序(合并排序)和插入排序(插入排序)而得出的排序算法,它在现实中有很好的效率.Tim Peters在2002年设计了该算法并在Python中使用是Python中list.sort的默认实现)。
        items = [6,20,8,19,56,23,87,41,49,53]
        print(timsort(items))
        :param arr:
        :return:
        """
        min_run = 32
        n = len(arr)

        for i in range(0, n, min_run):
            self.insertionSort(arr, i, min((i + min_run - 1), n - 1))

        size = min_run
        while size < n:
            for start in range(0, n, size * 2):
                midpoint = start + size - 1
                end = min((start + size * 2 - 1), (n - 1))
                merged_array = self.imerge(
                    left=arr[start:midpoint + 1],
                    right=arr[midpoint + 1:end + 1]
                )
                arr[start:start + len(merged_array)] = merged_array

            size *= 2

        return arr

    def countingSort(self,inputArray):
        """

        11 计数排序(Counting sort)inputArray = [2,2,0,6,1,9,9,7]
            print("Input array = ", inputArray)                                                                                                                                                                                                                                                                                sortedArray = countingSort(inputArray)
            print("Counting sort result = ", sortedArray)

        :return:
        """
        # Find the maximum element in the inputArray
        maxElement = max(inputArray)

        countArrayLength = maxElement + 1

        # Initialize the countArray with (max+1) zeros
        countArray = [0] * countArrayLength

        # Step 1 -> Traverse the inputArray and increase
        # the corresponding count for every element by 1
        for el in inputArray:
            countArray[el] += 1

        # Step 2 -> For each element in the countArray,
        # sum up its value with the value of the previous
        # element, and then store that value
        # as the value of the current element
        for i in range(1, countArrayLength):
            countArray[i] += countArray[i - 1]

            # Step 3 -> Calculate element position
        # based on the countArray values
        outputArray = [0] * len(inputArray)
        i = len(inputArray) - 1
        while i >= 0:
            currentEl = inputArray[i]
            countArray[currentEl] -= 1
            newPosition = countArray[currentEl]
            outputArray[newPosition] = currentEl
            i -= 1

        return outputArray

    def heapSort(self,array:list):
        """
        12 堆排序(Heap Sort)array = [13, 21, 15, 5, 26, 4, 17, 18, 24, 2]
        print(heap_sort(array))
        :param array:
        :return:
        """
        heap = []
        for element in array:
            heappush(heap, element)

        ordered = []

        # While we have elements left in the heap
        while heap:
            ordered.append(heappop(heap))

        return ordered

  

标签:Sort,arr,return,python,items,self,param,range,Algotrthms
From: https://www.cnblogs.com/geovindu/p/17530529.html

相关文章

  • python: PyCharm 2023.1打包项目成执行程序
        IDE最底部:pyinstaller-iheart.ico-Dmain.py     ......
  • python excel 模块优劣
    '''xlrd库:从excel中读取数据,支持xls、xlsxxlwt库:对excel进行修改操作,不支持对xlsx格式的修改xlutils库:在xlw和xlrd中,对一个已存在的文件进行修改openpyxl:主要针对xlsx格式的excel进行读取和编辑xlwings:对xlsx、xls、xlsm格式文件进行读写、格式修改等操作xlsxwriter:用来生......
  • Python教程(2)——开发python常用的IDE
    为什么需要IDE在理解IDE之前,我们先做以下的实验,新建一个文件,输入以下代码total_sum=0forxinrange(1,101): total_sum+=xprint(total_sum)非常非常简单的一个程序,主要就是计算1加到100的值,我们将它重命名为test.py,记住后缀名是改为py,然后保存。这时候打开cmd窗口,运......
  • python变量
    1.变量命名变量名只能包含字母、数字和下划线。变量名不能以数字开头。变量名不能包含空格,可使用下划线python关键字和函数名不能用作变量慎用1和大写O变量名默认用小写字母表示2.多个变量同时赋值x,y,z=1,2,3print(f"{x}{y}{z}")3.常量常量名默认用全大写......
  • 17.python-魔术方法
    python魔术方法-示例目录python魔术方法-示例特殊属性构造方法基本方法模拟容器类属性相关比较操作符运算符相关反运算增量赋值运算一元操作符类型转换上下文管理器参考资料特殊属性属性含义__name__类、函数、方法的名字,不能实例调用__module__类、函数、......
  • python数值变量
    1.整数#+-*/%2+3#乘方3**2(2+3)*42.浮点数#精度有误0.2+0.13.整数和浮点数#除的结果总是浮点数4/2#其他运算,一个整数一个浮点数,结果也是浮点数1+2.03.0**23**2.04.数中的下划线big=14_000_000_000print(big)......
  • Python的set集合详解
     Python还包含了一个数据类型——set(集合)。集合是一个无序不重复元素的集。基本功能包括关系测试和消除重复元素。集合对象还支持union(联合),intersection(交),difference(差)和sysmmetricdifference(对称差集)等数学运算。创建集合set大括号或set()函数可以用来创建集......
  • python字符串
    1.字符串函数name="jamesjacKSON"name.title()#字符串首字母大写,其余字母变小写name.upper()name.lower()2.在字符串中使用变量-f字符串(Python3.6引入的)first_name="ada"last_name="lovelace"full_name=f"{first_name}{last_name}"print(f......
  • 记录 python request ProxyError报错
    【出自】:https://zhuanlan.zhihu.com/p/350015032  侵删 解决办法:在原报错环境中使用下面命令重装低版本 urllib3:pipinstallurllib3==1.25.11 问题根源先查了一下 urllib3 的更新日志,应该是 1.26.0 的修改导致的:  按照这个更新日志,明明应该是增加了 HT......
  • python基础day38 并发编程
    进程概念进程、线程都是操作系统中的基本概念,也就是说进程和线程都是操作系统层面的东西,专业术语表达就是进程和线程都是由操作系统来调度的,而不是由我们程序员自己来操控的。在操作系统这门课里面,进程和线程是操作系统的概念,协程不是操作系统中的概念,而是我们程序员层面的协程......