创建一个字符串数组,总共5个元素,每个元素最多保存30个字符
,写一个函数排序整个数组。
//方法一:
#include
#include
void sort(char *arr[], int n)
{
char *tmp;
int i, j, k;
for (i = 0; i < n - 1; i++) //选择排序
{
k = i;
for (j = i + 1; j < n; j++)
{
if (strcmp(arr[k], arr[j])>0)
{
k = j;
}
}
tmp = arr[i];
arr[i] = arr[k];
arr[k] = tmp;
}
}
void print(char *arr[], int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
printf("%s\n", arr[i]);
}
}
int main()
{
int n = 5;
char *arr[] = { "abcde", "efghi", "hijkl", "bcdef", "defgh" };
sort(arr, n);
print(arr, n);
return 0;
}
//方法二:
#include
#include
int main()
{
char arr[5][30] = { "aaaa", "cccc", "bbbb", "eeee", "dddd" };
int i = 0, j = 0;
char tmp[30] = { 0 };
for (i = 0; i < 4; i++) //冒泡排序
{
for (j = 0; j < 4 - i; j++)
{
if (strcmp(arr[j], arr[j + 1]) > 0)
{
strcpy(tmp, arr[j]);
strcpy(arr[j], arr[j + 1]);
strcpy(arr[j + 1], tmp);
}
}
}
for (i = 0; i < 5; i++)
{
printf("%s\n", arr[i]);
}
return 0;
}
网站栏目:字符串数组排序问题
本文路径:
http://cxhlcq.com/article/pcdhpc.html