Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1743071
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Python/Ruby

2015-06-16 09:12:40


点击(此处)折叠或打开

  1. #selection sort
  2. def select(seq,start):
  3.     minIndex=start
  4.     for j in range(start+1,len(seq)):
  5.         if seq[minIndex] > seq[j]:
  6.             minIndex=j
  7.     return minIndex


  8. def selSort(seq):
  9.     for i in range(len(seq)-1):
  10.         minIndex=select(seq,i)
  11.         seq[i],seq[minIndex]=seq[minIndex],seq[i]

点击(此处)折叠或打开

  1. #merge sort
  2. def merge(seq,start,mid,stop):
  3.     lst=[]
  4.     i=start
  5.     j=mid

  6.     while i < mid and j < stop:
  7.         if seq[i] < seq[j]:
  8.             lst.append(seq[i])
  9.             i+=1
  10.         else:
  11.             lst.append(seq[j])
  12.             j+=1

  13.     while i< mid:
  14.         lst.append(seq[i])
  15.         i+=1

  16.     for i in range(len(lst)):
  17.         seq[start+i]=lst[i]

  18. def mergeSortRecursively(seq,start,stop):
  19.     if start >= stop-1:
  20.         return

  21.     mid=(start+stop)//2
  22.     mergeSortRecursively(seq,start,mid)
  23.     mergeSortRecursively(seq,mid,stop)
  24.     merge(seq,start,mid,stop)

  25. def mergeSort(seq):
  26.     mergeSortRecursively(seq,0,len(seq))


点击(此处)折叠或打开

  1. #quick sort
  2. import random
  3. def partition(seq,start,stop):
  4.     pivotIndex=start
  5.     pivot=seq[pivotIndex]
  6.     i=start+1
  7.     j=stop-1

  8.     while i <= j:
  9.         while i<= j and not pivot < seq[i]:
  10.             i+=1
  11.         while i<= j and pivot < seq[j]:
  12.             j-=1

  13.         if i< j:
  14.             tmp=seq[i]
  15.             seq[i]=seq[j]
  16.             seq[j]=tmp
  17.             i+=1
  18.             j-=1
  19.     seq[pivotIndex]=seq[j]
  20.     seq[j]=pivot
  21.     return j

  22. def quicksortRecursively(seq,start,stop):
  23.     if start >= stop -1:
  24.         return

  25.     pivotIndex=partition(seq,start,stop)
  26.     quicksortRecursively(seq,start,pivotIndex)
  27.     quicksortRecursively(seq,pivotIndex+1,stop)

  28. def quicksort(seq):
  29.     for i in range(len(seq)):
  30.         j=random.randint(0,len(seq)-1)
  31.         tmp=seq[i]
  32.         seq[i]=seq[j]
  33.         seq[j]=tmp
  34.     quicksortRecursively(seq,0,len(seq))


阅读(1528) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~