为了正常的体验网站,请在浏览器设置里面开启Javascript功能!

插入排序

2017-09-19 8页 doc 21KB 20阅读

用户头像

is_624976

暂无简介

举报
插入排序插入排序 插入排序: #include using namespace std; void insertion_sort(int * , int ); int main() { const int N=8; int a[N]={1,5,6,3,5,7,2,0}; insertion_sort(a,N); for(int i=0;i!=N;i++) { cout= 0 && a[j] > key){ //涵盖了插入位置在序列中部或头部两种情况 a[j+1] = a[j]; j--; } a[j+1] ...
插入排序
插入排序 插入排序: #include using namespace std; void insertion_sort(int * , int ); int main() { const int N=8; int a[N]={1,5,6,3,5,7,2,0}; insertion_sort(a,N); for(int i=0;i!=N;i++) { cout<= 0 && a[j] > key){ //涵盖了插入位置在序列中部或头部两种情况 a[j+1] = a[j]; j--; } a[j+1] = key; } } 选择排序: #include using namespace std; void selectsort(int * , int ); void swap(int *const,int *const); int main() { const int N=8; int a[N]={1,5,6,3,5,7,2,0}; selectsort(a,N); for(int i=0;i!=N;i++) { cout< #include #include long a[500100]; long cnt; //统计逆序数的cnt最大可能为(n-1)!(n为输入序列长度),因此设为long long型;另外,cnt设为全局变量免去了递归过程中的很多麻烦 void merge(long low, long mid, long high){ long len1 = mid-low+1; long len2 = high-mid; long * tmp1 = (long *)malloc((len1+1)*sizeof(long)); long * tmp2 = (long *)malloc((len2+1)*sizeof(long)); for(long i = 0; i < len1; i++) tmp1[i] = a[low+i]; for(long j = 0; j < len2; j++) tmp2[j] = a[mid+1+j]; tmp1[len1] = LONG_MAX; tmp2[len2] = LONG_MAX; long p1 = 0; long p2 = 0; for(long k = 0; k < len1+len2; k++){ if(tmp1[p1] <= tmp2[p2]){ a[low+k] = tmp1[p1]; p1++; } else{ a[low+k] = tmp2[p2]; p2++; cnt += len1-p1; //统计逆序数 } } free(tmp1); free(tmp2); } void merge_sort(long low, long high){ if(low < high){ long mid = (low+high)/2; merge_sort(low, mid); merge_sort(mid+1, high); merge(low, mid, high); } } int main(){ long n; while(1){ scanf("%ld", &n); if(n == 0) break; for(long i = 0; i < n; i++) scanf("%ld", &a[i]); cnt = 0; merge_sort(0, n-1); printf("%lld\n", cnt); for(long j=0;j!=n;j++) printf("%d",a[j]); } return 0; } 堆排序: #include using namespace std; void swap(int *,int *); void max_heapfy(int * , int, int); void heap_build(int * , int ); void heap_sort(int * , int ); int main() { int b[10]={1,4,6,3,8,2,9,3,7,4}; heap_sort(b, 10); for(int f=0;f!=10;f++) { cout< a[max]) //比较出max max = 2*k+1; if(2*k+2 < n && a[2*k+2] > a[max]) max = 2*k+2; if(max != k){ swap(&a[k], &a[max]); max_heapfy(a, n, max); //递归 } } void heap_build(int * a, int n){ for(int i = n/2-1; i >= 0; i--) //最后一个非叶结点为n/2-1 max_heapfy(a, n, i); } void heap_sort(int * a, int n){ heap_build(a, n); for(int i = n-1; i >= 1; i--){ swap(&a[i], &a[0]); max_heapfy(a, i, 0); } } #include #define MAXNUM 100 void bucksort(int arr[], int N, int M) { int count[MAXNUM]; for (int i=0; i<=M; i++) { count[i]=0; } for (int k=0; k
/
本文档为【插入排序】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。 本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。 网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。

历史搜索

    清空历史搜索