leetcode总结-- 排序算法(内部排序)

包括quick_sort(不稳定), merge_sort(稳定), bubble_sort(稳定), selection_sort(不稳定), insertion_sort(稳定)

code整理如下,我们可以发现所有的O( n2 )方法,都是

for i in xrange(len(nums) - 1):

说明它们都要进行len(nums) - 1次循环,例如bubble_sort要冒泡len(nums) - 1次。

ref: http://www.jianshu.com/p/ae97c3ceea8d
http://www.jianshu.com/p/f5baf7f27a7e

# your code goes here

def quick_sort(nums, low, high):

    p = nums[low]
    i,j = low, high

    while i < j:

        while j > i and nums[j] >= p:
            j -= 1

        nums[i] = nums[j]
        while i < j and nums[i] <= p:
            i += 1

        nums[j] = nums[i]
    nums[i] = p
    return i

def qsort(nums, low, high):

    if low < high:
        loc = quick_sort(nums, low, high)
        qsort(nums, low, loc - 1)
        qsort(nums, loc + 1, high)




def merge_sort(nums):

    if len(nums) > 1:   
        mid = len(nums) / 2
        left = nums[:mid]
        right = nums[mid:]
        merge_sort(left)
        merge_sort(right)


        i,j = 0,0
        k = 0

        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
                nums[k] = left[i]
                i += 1
            else:
                nums[k] = right[j]
                j += 1
            k += 1

        while i < len(left):
            nums[k] = left[i]
            i += 1
            k += 1

        while j < len(right):
            nums[k] = right[j]
            j += 1
            k += 1


def bubble_sort(nums):

    for i in xrange(len(nums) - 1):
        for j in xrange(len(nums) - 1 - i):# it is not length - 2 - i
            if nums[j] > nums[j + 1]:
                nums[j], nums[j + 1] = nums[j + 1], nums[j]



def selection_sort(nums):
    for i in xrange(len(nums) - 1): 

        min_idx = i
        for j in xrange(i + 1, len(nums)):
            if nums[j] < nums[min_idx]:
                min_idx = j
        if min_idx != i:
            nums[i], nums[min_idx] = nums[min_idx], nums[i]

def insertion_sort(nums):

    for i in xrange(len(nums) - 1):

        for j in xrange(i + 1, -1, -1):
            if nums[j] < nums[j - 1]:
                nums[j], nums[j - 1] = nums[j - 1], nums[j]
            else:
                break










if __name__ == '__main__':
    a = [1,4,8,2,9,2]
    #qsort(a,0, len(a) - 1)
    #merge_sort(a)
    #bubble_sort(a)
    #selection_sort(a)
    insertion_sort(a)
    print a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值