Python插入排序算法

时间:2014-03-13 12:58:35

标签: python algorithm python-2.7 sorting insertion-sort

基本上我正在尝试在python中编写插入排序算法,我不知道我哪里出错了

#!/usr/bin/env python
# coding: utf-8
import random
Array = random.sample(range(30), 5)
First = 1
Last = len(Array)
PositionOfNext = Last – 1
while PositionOfNext >= First:
    Next = Array(PositionOfNext)
    Current = PositionOfNext
    while (Current < Last) and (Next > Array[Current] + 1):
        Current = Current + 1
        (Array[Current] - 1) = Array[Current]
    Array[Current] = Next
    PositionOfNext = PositionOfNext - 1
print Array

2 个答案:

答案 0 :(得分:0)

修复一些语法问题和一些索引。

还替换:

(Array[Current] - 1) = Array[Current]

由:

Array[Current - 1], Array[Current] = Array[Current], Array[Current - 1]

代码已完成

#!/usr/bin/env python
# coding: utf-8
import random
Array = random.sample(range(30), 5)
print Array
First = 0
Last = len(Array) - 1
PositionOfNext = Last - 1
while PositionOfNext >= First:
    Next = Array[PositionOfNext]
    Current = PositionOfNext
    while  (Current < Last) and (Array[Current] > Array[Current + 1]):
        Current = Current + 1
        Array[Current - 1], Array[Current] = Array[Current], Array[Current - 1]
    Array[Current] = Next
    PositionOfNext = PositionOfNext - 1
print Array

答案 1 :(得分:0)

怎么样:

def insertion_sort(x):
    # insertion sort
    # we can optimize for desc, asc if we want to
    # advantages: online, O(nk) for nearly sorted
    x_sorted = [x[0]]
    x_unsorted = x[1::]
    for xx in x_unsorted:
        x_sorted.append(xx) # make room, and/or assume a sorted input list
        for i in range(len(x_sorted)-1):
            if xx < x_sorted[i]: # asc?
                x_sorted[i+1::] = x_sorted[i:-1] # shift old values
                x_sorted[i] = xx # insert new
                break # nothing to do in the inner loop form here on out
            i += 1
    return x_sorted