python 基本排序算法

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/6/24 下午7:54
# @Author  : lb
# @File    : test.py
import numpy as np
arr = np.random.randint(1000, size=1000)
print type(arr)


# 冒泡排序
def buble_sort(arr):
    return
    for i in xrange(len(arr)):
        for j in xrange(len(arr)-i-1):
            if arr[j] > arr[j+1]:
                tmp = arr[j+1]
                arr[j+1] = arr[j]
                arr[j] = tmp
    return arr

# 选择排序
def sel_sort(arr):
    for i in xrange(0, len(arr)):
        min = arr[i]
        pos = i
        for j in xrange(i, len(arr)):
            if arr[j] < min:
                pos = j
                min = arr[j]
        if pos != i:
            tmp = arr[pos]
            arr[pos] = arr[i]
            arr[i] = tmp
    return arr


# 插入排序
def insert_sort(arr):
    if len(arr) <= 1:
        return arr
    for i in xrange(1, len(arr)):
        tmp = arr[i]
        for j in xrange(i, -1, -1):
            if arr[j-1] > tmp:
                arr[j] = arr[j-1]
            else:
                break
        arr[j] = tmp
    return arr


# shell希尔排序
def shell_sort(arr):
    gap = len(arr) // 2
    while gap > 0:
        for i in xrange(gap, len(arr)):
            j = i
            tmp = arr[i]
            while j >= gap and arr[j-gap] > tmp:
                arr[j] = arr[j-gap]
                j -= gap
            arr[j] = tmp
        gap //= 2
    return arr
print shell_sort(arr)

 

上一篇:深入理解Python中range和xrange的区别


下一篇:Python2.x与3​​.x版本区别