三种排序算法
2010-10-23 15:03
609 查看
如下,三种排序算法的代码:插入、冒泡和快排,而快排实际上是对冒泡的一种改进。等复习算法的分治时,再将归并排序算法发上来。
#include<iostream> using namespace std; //插入排序法,算法的时间复杂度为o(n*n),稳定的排序方法 void insertSort(int a[],int length) { for(int i=1;i<length;i++) { if(a[i-1]>a[i]) { int temp=a[i]; int j; for(j=i-1;j>=0;j--) { if(a[j]>temp) { a[j+1]=a[j]; } else { break; } } if(j==0) { a[j]=temp; } else { a[j+1]=temp; } } } cout<<"用插入排序法排好序为:/n"; for(int i=0;i<length;i++) cout<<a[i]<<" "; cout<<endl; } //用冒泡法进行排序,算法的时间复杂度为o(n*n) ,稳定的排序方法 void maopaoSort(int a[],int length) { for(int i=0;i<length-1;i++) for(int j=0;j<length-1-i;j++) { if(a[j]>a[j+1]) { int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } cout<<"用冒泡排序法排好序为:/n"; for(int i=0;i<length;i++) cout<<a[i]<<" "; cout<<endl; } //快速排序,不稳定的排序,好的情况下时间复杂度为o(n*logn),坏的情况下时间复杂度为o(n*n) int Partion(int a[],int low,int high) { int i=low,j=high+1; int x=a[low]; while(true) { while(a[++i]<x&&i<j); while(a[--j]>x); if(i>=j) break; int temp=a[i]; a[i]=a[j]; a[j]=temp; } a[low]=a[j]; a[j]=x; return j; } void QSort(int a[],int low,int high) { if(low<high) { int pivot=Partion(a,low,high); QSort(a,low,pivot-1); QSort(a,pivot+1,high); } } int main() { int a[]={4,5,1,7,6}; insertSort(a,5); int b[]={8,0,1,5,3}; maopaoSort(b,5); int a1[]={3,4,-1,2,5,9}; QSort(a1,0,5); for(int i=0;i<6;i++) cout<<a1[i]<<" "; cout<<endl; system("pause"); return 0; }
相关文章推荐
- C语言中三种常见排序算法分析
- 单链表的三种排序算法
- C语言中冒泡法、选择法、插入法三种常见排序算法分析
- C语言中三种常见排序算法分析
- 常见的三种排序算法(堆排、快排、归并排序)的比较总结
- java中的三种排序算法详解(直接选择.冒泡.插入)
- java常用三种排序算法---(插入,冒泡,顺序)及其时间复杂度
- 三种数组排序算法(冒泡排序、选择排序、插入排序、二分查找法)
- 三种全排序算法详解
- 关于三种基本排序算法的速度直观分析
- 【基础排序算法】最常见的三种排序算法(冒泡、插入、选择)
- 数据结构之程序性能检测(一):三种排序算法·对比
- 三种排序算法的C语言实现--直接插入、希尔、堆排序
- Java三种常见的排序算法:冒泡,选择,插入
- [排序算法]--直接插入排序的三种实现(Java)
- 动态生成数组,随机生成一定范围的随机数,三种常用排序算法
- 算法:三种简单排序算法
- 三种初级排序算法(冒泡、选择、直接插入)java实现及其性能比较
- 三种简单的排序算法
- 用Python实现的三种排序算法