#include "stdio.h"
#define len (100) /* 本程序不考虑输入的字符串长度超过用 len 能正常处理的情况 */
int compare(char *sa, char *sb);
void main(){
char s[3][len];
int i, mid, A[10], B[10], j, CountCompare, CountExchange, tmp, min;
printf("从键盘输入三个字符串,将它们由小到大的顺序输出。\n");
for (i = 0; i < 3; i++){
printf("请输入第 %d 个字符串: ", i + 1);
scanf("%s", s[i]);
}
for (i = 0;; i++)
if ((compare(s[i], s[(i+1) % 3]) <= 0) && (compare(s[i], s[(i+2) % 3]) <= 0)){
if (compare(s[(i + 1) % 3], s[(i + 2) % 3]) <= 0) mid = (i + 1) % 3;
else mid = (i + 2) % 3;
printf("最小的: %s\n", s[i]);
printf("中间的: %s\n", s[mid]);
printf("最大的: %s\n", s[0+1+2-i - mid]);
break;
}
printf("\n下面用分别用冒泡法和选择法对 10 个输入的整数排序\n");
for (i = 0; i < 10; i++){
printf("请输入第 %d 个整数(-32768..32767): ", i + 1);
scanf("%d", &(A[i]));
B[i] = A[i];
}
/* 冒泡法 */
CountCompare = CountExchange = 0;
for (i = 10-1; i > 0; i--)
for (j = 0; j < i; j++){
CountCompare++;
if (A[j] > A[j + 1]){
tmp = A[j]; A[j] = A[j + 1]; A[j + 1] = tmp;
CountExchange++;
}
}
printf("\n用冒泡法共用 %d 次数据比较, %d 次数据交换, 排序结果如下:\n",
CountCompare, CountExchange);
for (i = 0; i < 10-1; i++) printf("%d, ", A[i]);
printf("%d\n", A[10-1]);
/* 选择法 */
CountCompare = CountExchange = 0;
for (i = 0; i < 10; i++){
min = i;
for (j = i + 1; j < 10; j++){
CountCompare++;
if (B[j] < B[min]) min = j;
}
if (min != i){
tmp = B[min]; B[min] = B[i]; B[i] = tmp;
CountExchange++;
}
}
printf("\n用选择法共用 %d 次数据比较, %d 次数据交换, 排序结果如下:\n",
CountCompare, CountExchange);
for (i = 0; i < 10-1; i++) printf("%d, ", B[i]);
printf("%d\n", B[10-1]);
printf("按任意键退出程序.\n"); getchar();
}
/* 比较字符串, sa > sb, 返 1, sa == sb, 返 0, sa < sb, 返 -1 */
int compare(char *sa, char *sb){
if ((sa == NULL) || (sb == NULL)){
printf("error: empty pointer!\n");
abort();
}
while (*sa == *sb){
if (*sa == '\0') return 0;
sa++; sb++;
}
if (*sa > *sb) return 1; else return - 1;
}