Python实现冒泡,插入,选择排序简单实例,python冒泡


本文所述的Python实现冒泡,插入,选择排序简单实例比较适合Python初学者从基础开始学习数据结构和算法,示例简单易懂,具体代码如下:

# -*- coding: cp936 -*-
#python插入排序
def insertSort(a):
  for i in range(len(a)-1):
    #print a,i 
    for j in range(i+1,len(a)):
      if a[i]>a[j]:
        temp = a[i]
        a[i] = a[j]
        a[j] = temp
  return a

#Python的冒泡排序  
def bubbleSort(alist):
  for passnum in range(len(alist)-1,0,-1):
    #print alist,passnum
    for i in range(passnum):
      if alist[i]>alist[i+1]:
        temp = alist[i]
        alist[i] = alist[i+1]
        alist[i+1] = temp
  return alist

#Python的选择排序 
def selectionSort(alist):
  for i in range(len(alist)-1,0,-1):
    maxone = 0
    for j in range(1,i+1):
      if alist[j]>alist[maxone]:
        maxone = j
    temp = alist[i] 
    alist[i] = alist[maxone]
    alist[maxone] = temp 
  return alist

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

感兴趣的朋友可以动手测试一下本文实例,相信会有新的收获。


选择排序,快速排序,冒泡排序,堆排序,插入排序,基排序的程序的运行速度

要看时间复杂度罗。
O(n^2),O(n^2),O(n^2),O(nlog 2 n),O(nlog 2 n),O(nlog 2 n),
 

写排序的几种算法,简单选择排序,直接插入排序,冒泡排序,详细点

这个我知道,希望能帮助你!
/* 排序 */
#include"stdio.h"
#define M 50

void bubblesort(int a[], int n);
void insertsort(int a[],int n);
void selectsort(int a[],int n);
void main()
{
int a[M],i,n,j,locate,kk;
clrscr();
while(1)
{
window(1,1,80,6);clrscr();
printf("\n ----------------------------------\n\n");
printf(" 1.create 2.bubblesort 3. insertsort 4.selectsort\n");
printf(" 0.exit\n");
printf("input your choice:");
scanf("%d",&kk);
switch(kk)
{
case 1:window(1,8,80,25);clrscr();
printf("\ninput number: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n");
for(i=1;i<=n;i++)
printf("%5d",a[i]);
break;
case 2:window(1,8,80,25);clrscr();
bubblesort (a,n);
break;

case 3:window(1,8,80,25);clrscr();
insertsort(a,n);
break;
case 4:window(1,8,80,25);clrscr();
selectsort(a,n);
break;
default:exit(0);
}
}

}
void selectsort(int a[],int n)/*简单选择排序*/
{
int i,j,k,temp,m;
for(i=1;......余下全文>>
 

评论关闭