T O P
Image

Algorithm

冒泡排序 和 快速排序

实现两个常用的排序方法

  • By - C灵C

  • 2021年3月15日 15:43





冒泡排序

        外层循环从1到n-1,内循环从当前外层的元素的下一个位置开始,依次和外层的元素比较,出现逆序就交换,通过与相邻元素的比较和交换来把小的数交换到最前面。


202191115056488.gif

 def bubbleSort(array):
    if len(array) < 2:
        return array
    else:
        isSorted = False
        counter = 0
        while not isSorted:
            isSorted = True
            for idx in range(len(array) - 1 - counter):
                if array[idx] > array[idx + 1]:
                    isSorted = False
                    (array[idx + 1], array[idx]) = (array[idx], array[idx + 1])
            counter += 1
        return array
快速排序
    通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,
    则可分别对这两部分记录继续进行排序,以达到整个序列有序。
    1、选定Pivot中心轴
    2、从R指针开始,将大于Pivot的数字放在Pivot的右边
    3、将小于Pivot的数字放在Pivot的左边
    4、分别对左右子序列重复前三步操作


202191115544386.gif


def quickSort(array):
    print(array)
    if len(array) < 2:
        return array
    else:
        pivot_index = 0
        pivot = array[pivot_index]
        less_part = [i for i in array[pivot_index+1:] if i <= pivot]
        large_part = [i for i in array[pivot_index+1:] if i > pivot]
        return quickSort(less_part) + [pivot] + quickSort(large_part)


Image

Algorithm

冒泡排序 和 快速排序

BY - C灵C