插入排序(算导2.1-2)
2016-11-16 15:17 yojiaku 阅读(209) 评论(0) 编辑 收藏 举报//============================================================================ // Name : Insertion.cpp // Author : yojiaku // Version : // Copyright : 算法导论-插入排序简单实现(只有mian函数)-按非降序排列 // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; int main() { int num[] = {2, 3, 8, 7, 0}; int key(0); int i(0); for(int j = 1; j < 5; j++){ key = num[j]; // insert num[j] into the sorted num[0, ..., j-1] i = j - 1; while(i >= 0 && num[i] < key){ num[i+1] = num[i]; i = i -1; } num[i+1] = key; } for(int j = 0; j < 5; j++){ cout << num[j] << " "; } cout << endl; return 0; }
运行结果:
8 7 3 2 0
伪代码:
INSERTION-SORT(A) for j = 2 to A.length key = A[j] // insert A[j] into the sorted sequence A[1, …, j-1] I = j – 1 while(i > 0 and A[i] < key) A[i+1] = A[i] I = I -1 A[i+1] = key
//============================================================================ // Name : Insertion.cpp // Author : yojiaku // Version : // Copyright : 算法导论-插入排序简单实现(只有mian函数)-按非升序排列 // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; int main() { int num[] = {8, 3, 8, 7, 0}; int key(0); int i(0); for(int j = 1; j < 5; j++){ key = num[j]; // insert num[j] into the sorted num[0, ..., j-1] i = j - 1; while(i >= 0 && num[i] > key){ num[i+1] = num[i]; i = i -1; } num[i+1] = key; } for(int j = 0; j < 5; j++){ cout << num[j] << " "; } cout << endl; return 0; }
运行结果:
0 3 7 8 8
伪代码:
INSERTION-SORT(A) for j = 2 to A.length key = A[j] // insert A[j] into the sorted sequence A[1, …, j-1] I = j – 1 while(i > 0 and A[i] > key) A[i+1] = A[i] I = I -1 A[i+1] = key
上面用超级简单的c++代码实现了插入排序,是用的静态数组,不太好,下面稍微改进了一下,用了vector,但是还是不是很好,我会持续改进的!
//============================================================================ // Name : Insertion.cpp // Author : yojiaku // Version : // Copyright : 算法导论-插入排序简单实现(只有mian函数)-按非升序排列-use vector // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <vector> using namespace std; using std::vector; int main() { //int num[] = {8, 3, 8, 7, 0}; vector<int> num; cout << "请输入大于或等于0的数字进行排序,输出小于0的数字默认输入结束" << endl; int temp; while(cin >> temp && temp >= 0){ num.push_back(temp); } int length = num.size(); cout << "一共有" << length << "个数字进行比较" << endl; int key(0); int i(0); for(int j = 1; j < length; j++){ key = num[j]; // insert num[j] into the sorted num[0, ..., j-1] i = j - 1; while(i >= 0 && num[i] > key){ num[i+1] = num[i]; i = i -1; } num[i+1] = key; } for(int j = 0; j < length; j++){ cout << num[j] << " "; } cout << endl; return 0; }
运行结果:
请输入大于或等于0的数字进行排序,输出小于0的数字默认输入结束
1 3 3 1 5 2 9 0
-1
一共有8个数字进行比较
0 1 1 2 3 3 5 9
上面这个是用了size()来确定vector的大小以及for循环的条件,在我没找到更好的办法时就先这样吧。