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

你可能感兴趣的:(leetcode)