#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char *str[] = { "hello", "change", "world", "come", "on" }; //指针数组,每一个都是字符指针 int i = 0; int j = 0; int flag; int size = sizeof(str) / sizeof(str[0]); for (i = 0; i < size - 1; i++) //n个字符串,交换(n-1)次 { flag = 1; //设置标志位,优化冒泡 for (j = 0; j <size - 1 - i; j++) { if (strcmp(str[j], str[j + 1]) > 0) //常量字符串在空间的地址 { char *tmp = NULL; //交换地址 tmp = str[j]; str[j] = str[j + 1]; str[j + 1] = tmp; flag = 0; } } if (flag) //说明未进入if内部,即尚未交换已经是所需的输出顺序 { break; } } for (i = 0; i < size; i++) { printf("%s ", str[i]); } printf("\n"); system("pause"); return 0; }
原文地址:http://10740184.blog.51cto.com/10730184/1712540