【问题标题】:Python Insertion Sort AlgorithmPython 插入排序算法
【发布时间】:2014-03-13 12:58:34
【问题描述】:

基本上我正在尝试在 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

【问题讨论】:

  • 我没有经历过,但通常最好明确说明预期的输出是什么以及你得到的是什么?
  • 哦,对了,对不起,输出将是获取数组并使用选择排序过程对其进行排序,我现在得到的错误是第 7 行 PositionOfNext = Last – 1 ^ SyntaxError: invalid syntax跨度>
  • 删除第 7 行的“-”字符并再次键入。它不是-,而是其他一些字符。您可能从某个地方复制了代码。

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


【解决方案1】:

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

同时替换:

(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

【讨论】:

  • 我知道这可能只是语法问题,但我无法理解,非常感谢
  • 没问题,我对python也很陌生,仍然在语法上挣扎。
【解决方案2】:
def insertionSort(alist):
   for index in range(1,len(alist)):

     currentvalue = alist[index]
     position = index

     while position>0 and alist[position-1]>currentvalue:
         alist[position]=alist[position-1]
         position = position-1

     alist[position]=currentvalue

alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)

The Insertion Sort

【讨论】:

    【解决方案3】:

    怎么样:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多