排序算法-插入排序 Insertion Sort Θ(n-n)
2016-05-04 16:45
519 查看
还在读书的孩子要好好珍惜读书的日子啊。
多羡慕你们完全不用为生活操心,每天只需要一心扑在学习或者自己喜欢的事情上。
多羡慕你们完全不用为生活操心,每天只需要一心扑在学习或者自己喜欢的事情上。
版本一
#include<iostream> using namespace std; void swap(int* a, int* b) { //*a = *a + *b; //*b = *a - *a; //*a = *a - *b; int temp = *a; *a = *b; *b = temp; } void InsertSort(int A[], int size) { for (int j = 1; j < size; j++) { for (int i = j - 1; i >= 0; i--) { if (A[i] > A[i + 1]) swap(A[i], A[i + 1]); } } } int main() { // int A[] = { 5,2,4,6,1,3 }; // 假设个数未知 int A[6] = { 0 }; int x = 0; while (cin>>A[x]) { x++; } int size = sizeof(A) / sizeof(int); InsertSort(A, size); for (int i = 0; i < size; i++) { cout << A[i] << " "; } return 0; }
版本二
#include <iostream> using namespace std; typedef int Item; #define key(A) (A) #define less(A, B) (key(A) < key(B)) #define exch(A, B) {Item t = A; A = B; B = t;} #define compexch(A, B) if(less(B, A)) exch(A, B) void print(int a[], int size) { for (int i = 0; i < size; i++) cout << a[i] << " "; cout << endl; } void insertion_sort(Item a[], int size) { for (int i = 0; i < size; i++) compexch(a[0], a[i]); for (int i = 1; i < size; i++) { int j = i; Item v = a[i]; while(less(v, a[j-1])) { a[j] = a[j-1]; j--; } a[j] = v; } } int main(int argc, char* argv[]) { int A[] = { 8,7,6,5,4,3,2,1 }; int size = sizeof(A)/sizeof(int); insertion_sort(A, size); print(A, size); return 0; }
相关文章推荐
- 关于html的下载功能详解
- [Mac] Atom 必备插件集合
- Android getResources()方法
- java中文筛选分词对比
- 函数赋值给变量
- 打印100-999以内的水仙花数
- Spark组件之GraphX学习11--PageRank例子(PageRankAboutBerkeleyWiki)
- java基础学习总结——数组
- JMeter事务控制器(Transaction controller)
- 用指针作为函数参数
- python——pip安装包教程
- jQuery学习之jQuery Ajax用法详解
- Linux下随机10字符病毒的清除
- kafka+zookeeper环境配置(Mac 或者 linux环境)
- HTTP协议详解(真的很经典)
- MultiDex 官方教你解决64K方法
- 深度优先搜索
- 练习打字第二天!
- linux中的kill详解
- Android 耳机状态监听