插入排序
非降序排列
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 const int N = 10; 5 int a[N]; 6 int main() { 7 //freopen("in.txt", "r", stdin); 8 int n; 9 scanf("%d",&n); 10 for (int i = 0; i < n; i++) 11 scanf("%d",a + i); 12 for (int i = 1; i < n; i++) { 13 int key = a[i]; 14 int j; 15 for (j = i; j > 0; j--) { 16 if (key >= a[j - 1])break; 17 a[j] = a[j - 1]; 18 } 19 a[j] = key; 20 } 21 for (int i = 0; i < n; i++) 22 printf("%d ",a[i]); 23 return 0; 24 }
非升序排列
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 const int N = 10; 5 int a[N]; 6 int main() { 7 //freopen("in.txt", "r", stdin); 8 int n; 9 scanf("%d",&n); 10 for (int i = 0; i < n; i++) 11 scanf("%d",a + i); 12 for (int i = 1; i < n; i++) { 13 int key = a[i]; 14 int j; 15 for (j = i; j > 0; j--) { 16 if (key <= a[j - 1])break; 17 a[j] = a[j - 1]; 18 } 19 a[j] = key; 20 } 21 for (int i = 0; i < n; i++) 22 printf("%d ",a[i]); 23 return 0; 24 }
posted on 2014-03-29 16:59 shijianupc 阅读(120) 评论(0) 编辑 收藏 举报