1306. Sorting Algorithm
来源:互联网 发布:电视会被网络取代吗 编辑:程序博客网 时间:2024/06/07 06:37
题解:
水题一道,写个堆排序练练手。
今天上数据结构课,老师问了一个问题:实际应用中,快速排序为何比堆排序应用更加广泛?答案:堆排比较的几乎都不是相邻元素,对cache极不友好,这才是很少被采用的原因。
Code:
#include <iostream>#include <stdio.h>using namespace std;void swap_m(int & a,int & b){ int tmp = b; b = a; a = tmp;}void heap_sort(int i,int * s,int last){ int L = 2*i, R = 2*i+1; if (L>last&&R>last) return ; int Max_LR = -1; if (R<=last&&L>last) Max_LR = R; if (L<=last&&R>last) Max_LR = L; if (R<=last&&L<=last) Max_LR = (s[L]<s[R])?R:L; if (s[Max_LR]>s[i]) { swap_m(s[Max_LR],s[i]); heap_sort(Max_LR, s, last); }}int main(){ int N,I; while(scanf("%d%d",&N,&I)&&(N!=0||I!=0)) { int * s = new int [N+1]; s[0] = N; for (int i = 1;i<=N;i++) scanf("%d",&s[i]); for (int i = N/2;i>=1;i--) heap_sort(i,s,N); for (int i = N;i>=1;i--) { swap_m(s[i], s[1]); heap_sort(1, s, i-1); } //for(int i =1;i<=N;i++) // printf("%d ",s[i]); for (int i = 1;i<=N;i+=I) if (i==1) printf("%d",s[i]); else printf(" %d",s[i]); printf("\n"); } //printf("\n"); return 0;}
阅读全文
0 0
- 1306. Sorting Algorithm
- sicily--1306. Sorting Algorithm
- 1306. Sorting Algorithm
- Sicily 1306. Sorting Algorithm
- sicily 1306. Sorting Algorithm
- 1306. Sorting Algorithm
- Sorting Algorithm
- Sorting Algorithm
- Sorting Algorithm
- BST sorting algorithm
- sorting algorithm排序算法
- Algorithm Review: Sorting
- 1007. Sorting Algorithm
- interview sorting algorithm summary
- Sorting Algorithm-Bubble Sort
- Sorting Algorithm-Shell Sort
- Sorting Algorithm-PreKnowledge
- Sorting Algorithm-Heap Sort
- JS复习 -- 作用域链
- 1-5·Linux中帮助命令
- Python编程:从入门到实践的动手试一试答案(第七章)
- OpenCV计算机视觉编程攻略(第2版)代码
- Android显示原理简介(阿里巴巴)
- 1306. Sorting Algorithm
- xampp浏览器不能直接访问本地127.0.0.1,报错Something is wrong with the XAMPP installation :-(
- Maven deploy配置方法
- python文件批量改名
- 欢迎使用CSDN-markdown编辑器
- Android java常用的正则表达式
- 使用Spring Boot操作Hive JDBC时,启动时报出错误:NoSuchMethodError: org.eclipse.jetty.servlet.ServletMapping.setDef
- dubbo+zookeeper+spring整合(从菜鸟开始)
- c语言作业杨枝10.28/10.29