各种排序算法
来源:互联网 发布:linux下压缩文件命令 编辑:程序博客网 时间:2024/05/16 11:38
</pre><pre name="code" class="cpp">
#include<stdio.h>int a[101];void insertsort(int a[],int n){ int i,j,temp; for(i=2;i<=n;i++) { if(a[i]<a[i-1]) //a[i]插入的是一个有序子表 { temp=a[i]; //循环后移 for(j=i-1;a[j]>temp;j--) { a[j+1]=a[j]; } a[j+1]=temp; } }}void quicksort(int left,int right){ //重要!! if(right<left) return; int i,j,temp; int t; //存放中间变量 temp=a[left]; i=left;j=right; while(i!=j) { //顺序很重要,要从右往左找 while(a[j]>=temp&&i<j) j--; while(a[i]<=temp&&i<j) i++; if(i<j) { t=a[i]; a[i]=a[j]; a[j]=t; } } //将基数归位 a[left]=a[i]; a[i]=temp; //递归 quicksort(left,i-1); quicksort(i+1,right); return;}int main(){ int i,n; scanf("%d",&n); for(i=1;i<=n;i++) scanf("%d",&a[i]); insertsort(a,n); quicksort(1,n); //快速排序调用 //输出排序后的结果 for(i=1;i<=n;i++) printf("%d ",a[i]); return 0;}
插入排序的时间复杂度:
当最好的情况,也就是要排序的数组本身就是有序的,数组没有移动的情况,时间复杂度为o(n);最坏的情况,即待排序的数组是逆序的时间复杂度为o(n^2)。同样为o(n^2)的时间复杂度,直接插入排序比选择排序和冒泡排序的性能要好一些。
快排的时间复杂度为o(NlogN)
归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。归并排序是稳定的排序,即相等的元素的顺序不会改变。
时间复杂度为O(nlogn) ,空间复杂度为O(n)。
//合并void Merge(int sourceArr[],int tempArr[], int startIndex, int midIndex, int endIndex){ int i = startIndex, j=midIndex+1, k = startIndex; while(i!=midIndex+1 && j!=endIndex+1) { if(sourceArr[i] >= sourceArr[j]) tempArr[k++] = sourceArr[j++]; else tempArr[k++] = sourceArr[i++]; } while(i != midIndex+1) tempArr[k++] = sourceArr[i++]; while(j != endIndex+1) tempArr[k++] = sourceArr[j++]; for(i=startIndex; i<=endIndex; i++) sourceArr[i] = tempArr[i];}void Msort(int SR[],int TR[],int begin,int end){ int m; //SR[]为待排数组,TR为排好数组 if(begin==end) TR[begin]=SR[begin]; else { m=(begin+end)/2; Msort(SR,TR,begin,m); Msort(SR,TR,m+1,end); Merge(SR,TR,begin,m,end); }}
0 0
- 【算法】各种排序算法
- 各种排序算法
- 各种排序算法
- 各种排序算法收集
- 各种排序算法
- 各种排序算法小结
- 各种排序算法小结
- 各种内部排序算法!
- 各种排序算法小结
- 各种排序算法
- 各种排序算法
- 各种排序算法介绍
- 各种排序算法
- 各种排序算法比较
- 各种排序算法
- 各种排序算法
- C++各种排序算法
- 各种排序算法
- 防止IE被修改
- c++构造函数中调用虚函数的原理剖析
- DNS查询指令:host 、nslookup 、dig 详解
- Maven学习总结(一)——Maven入门
- char* 和char[]的区别
- 各种排序算法
- Myeclipse server报错 Could not create the view: An unexpected exception was thrown.问题解决
- JAVA中protected的作用
- iOS证书的选择
- PDO多种方式取得查询结果
- 正则表达式-学习
- openERP 简单模块 1
- 2016年中总结和展望
- 裁剪特定时长音乐需求之Audacity