Python中使用插入排序算法的简单分析与代码示例

WBOY
Release: 2016-06-10 15:05:03
Original
1135 people have browsed it

问题描述

将一组随机排列的数字重新按照从小到大的顺序排列。

插入算法

每次从数组中取一个数字,与现有数字比较并插入适当位置。

如此重复,每次均可以保持现有数字按照顺序排列,直到数字取完,即排序成功。

这很像打牌时的抓牌情况,

第一个条件:保持手上的牌的顺序是正确的
第二个条件:每次抓到新的牌均按照顺序插入手上的牌中间。
保证这两条不变,那么无论抓了几张牌,最后手上的牌都是依照顺序排列的。

Python 实现:

def insertion_sort(n):
 if len(n) == 1:
  return n
 b = insertion_sort(n[1:])
 m = len(b)
 for i in range(m):
  if n[0] <= b[i]:
   return b[:i]+[n[0]]+b[i:]
 return b + [n[0]]
Copy after login


另一个版本:

def insertion_sort(lst):
 if len(lst) == 1:
  return lst

 for i in xrange(1, len(lst)):
  temp = lst[i]
  j = i - 1
  while j >= 0 and temp < lst[j]:
   lst[j + 1] = lst[j]
   j -= 1
  lst[j + 1] = temp
 return lst
Copy after login

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!