【发布时间】:2018-09-22 15:52:56
【问题描述】:
任何帮助将不胜感激。 我正在尝试使用带有以下代码的冒泡排序按字母顺序对包含在数组中的 12 个字符串进行排序:
#include <stdio.h>
#include <string.h>
int main()
{
//initialising variables and the array
char *DT [12] = { "James Smith DT01 DT265A", "John Murphy DT02 DT265A", "Robert Lam DT03 DT265A", "Michael Martin DT04 DT265A", "William Brown DT05 DT265A", "David Roy DT06 DT265A", "Richard Tremblay DT07 DT265A", "Joseph Lee DT08 DT265A", "Thomas Gagnon DT09 DT265A", "Charles Wilson DT10 DT265A", "Chris Philips DT11 DT265A", "Henry Hill DT12 DT265A" } ;
char temp[100];
int n = sizeof(DT)/sizeof(DT[0]);
//Implementing Algorithm using bubble sort to sort string array
//
for (int j = 0 ; j < n - 1 ; j++ )
{
for (int i = j + 1 ; i < n ; i++ )
{
if( strcmp(DT[j], DT[i]) > 0 )
{
strcpy(temp, DT[j]);
strcpy(DT[j], DT[i]);
strcpy(DT[i], temp);
}//end if
}//end for
}//end for
printf("Strings in sorted order are : ");
for (int i=0; i<n; i++)
{
printf("\n String %d is %s", i+1, DT[i]);
}
getchar();
getchar();
return 0;
}//end main()
我得到的输出是:
按排序顺序排列的字符串是:
字符串 1 是 A
字符串 2 是 A
字符串 3 是 2vid Roy DT06 DT265A
字符串 4 是 Roy DT06 DT265A
弦 5 是 Charles Wilson DT10 DT265A
字符串 6 是
字符串 7 是 Chris Philips DT11 DT265A
字符串 8 是 06 DT265A
字符串 9 是 avidRoy DT06 DT265A
字符串 10 是 mith DT01 DT265David Roy Dyy DT06 DT265A
字符串 11 是 y DT06 DT265A
字符串 12 是 y DT06 DT265A
【问题讨论】:
-
有什么问题?
-
char *DT [12]不确定,但它不是文字数组吗? -
这不是冒泡排序。这是一种选择排序。
标签: c string algorithm sorting bubble-sort