黑马程序员技术交流社区
标题:
C语言学习笔记之字符串排序的两种方法
[打印本页]
作者:
chunhuayun
时间:
2015-9-27 21:12
标题:
C语言学习笔记之字符串排序的两种方法
输入5个国家的名字并按照字母顺序排序后输出
代码实现如下
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//冒泡排序法
void sortByBulle(char * names[], int len){
char *temp = names[0];
for (int i = 0; i < len -1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
if (strcmp(names[j], names[j + 1]) > 0) {
temp = names[j];
names[j] = names[j + 1];
names[j + 1] = temp;
}
}
}
}
//选择排序法
void sortBySelection(char * names[], int len){
char *temp = NULL;
for (int i = 0; i < len - 2; i++) {
for (int j = i + 1; j < len; j++) {
if (strcmp(names[i], names[j]) > 0) {
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
}
int main(int argc, const char * argv[])
{
int len = 8;
char *names[] = {"CHINA","AFRICA","KOREA","AMERICA","FRANCE","INDIA","BRITAIN","AUSTRALIA"};
sortByBulle(names, len);
printf("Bulle sort:\n");
for (int i = 0; i < len; i++) {
printf("%s\n", *(names+i));
}
char *names2[] = {"CHINA","AFRICA","KOREA","BRITAIN","FRANCE","INDIA","AMERICA","AUSTRALIA"};
printf("Selection sort:\n");
sortBySelection(names2, len);
for (int i = 0; i < len; i++) {
printf("%s\n", *(names2 + i));
}
return 0;
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2