排序
1、选择排序
代码实现:
/* 2017年6月19日14:46:17 功能:选择排序的降序排序 */ #include"stdio.h" #define N 8 int main() { int i, j, m, temp; int a[N]; for(i = 0; i < N; i++) { printf("please input a number :" ); scanf("%d",&m); a[i] = m; } printf("The old array is: "); printf("\n"); for(i = 0; i < N; i++) { printf("%d\t",a[i] ); } printf("\n" ); for(i = 0;i < N; i++) { for(j = i+1; j < N; j++) { if(a[i] < a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } printf("The new array is: "); printf("\n"); for(i = 0; i < N; i++) { printf("%d\t",a[i] ); } printf("\n" ); return 0; } /* 总结: 在VC++6.0中显示的结果为: ———————————————————————————————— please input a number :2 please input a number :4 please input a number :8 please input a number :9 please input a number :6 please input a number :1 please input a number :9 please input a number :5 The old array is: 2 4 8 9 6 1 9 5 The new array is: 9 9 8 6 5 4 2 1 ———————————————————————————————— */
2、冒泡排序
代码实现:
/* 2017年6月19日15:17:40 功能:冒泡排序的降序排序 */ #include"stdio.h" #define N 8 int main() { int a[N]; int i, j, m, temp; for(i = 0; i < N; i++) { printf("please input a number :" ); scanf("%d",&m); a[i] = m; } printf("The old array is : "); printf("\n"); for(i = 0; i < N; i++) { printf("%d\t",a[i]); } printf("\n" ); for(i = 0; i < N; i++) { for(j = 0; (j < N - i)&&(j+1 < N - i); j++) { if(a[j]< a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } printf("The new array is : "); printf("\n"); for(i = 0; i < N; i++) { printf("%d\t",a[i]); } printf("\n" ); return 0; } /* 总结: 在VC++6.0中显示的结果为: ———————————————————————————————— please input a number :2 please input a number :4 please input a number :8 please input a number :4 please input a number :9 please input a number :5 please input a number :3 please input a number :1 The old array is : 2 4 8 4 9 5 3 1 The new array is : 9 8 5 4 4 3 2 1 ———————————————————————————————— */
时间: 2024-10-11 11:09:41