C/C++の宿題のまとめ@Wiki

文字列のソート

最終更新:

匿名ユーザー

- view
管理者のみ編集可
183 :デフォルトの名無しさん :2005/11/02(水) 15:04:20
[1] 授業単元:プログラミング実習
[2] 問題文(含コード&リンク):
文字列を用いて5人文の名前を入力し表示するプログラムを作りなさい。
ただし名前の頭文字のアルファベット順に並べ変えて表示すること
[3] 環境
 [3.1] OS: Linux
 [3.2] コンパイラ名とバージョン: gcc
 [3.3] 言語: C
[4] 期限: ([2005年11月06日まで]
[5] その他の制限:配列あたりまで習っています。
なんか急に難しくなってきた気がしてお手上げです。
どうか宜しくお願いします。

184 :デフォルトの名無しさん :2005/11/02(水) 15:20:42
>>183
#include <stdio.h>
#include <string.h>
typedef char string[256];
int main() {
 int i, j; string s[5], tmp;
 for (i = 0; i < 5; ++i) { printf("name%d: ", i); scanf("%s", s[i]); }
 for (i = 0; i < 5; ++i) /* sort */
  for (j = i+1; j < 5; ++j)
   if (strcmp(s[i], s[j]) > 0)
    strcpy(tmp, s[i]), strcpy(s[i], s[j]), strcpy(s[j], tmp); /* swap */
 for (i = 0; i < 5; ++i) printf("%s\n", s[i]);
}

185 :デフォルトの名無しさん :2005/11/02(水) 15:23:10
/*
* 文字列を用いて5人文の名前を入力し表示するプログラムを作りなさい。
* ただし名前の頭文字のアルファベット順に並べ変えて表示すること
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NAMEMAX 20
/* クイックソートかバブルか選択 */
#define BUBBLE 0
#define QUICK 1

typedef char Name[NAMEMAX+1];

void swap(Name*, int, int);
int comp(const Name*, const Name*);

int main(void)
{
Name names[5], tmp;
int i, j;

for (i=0;i<5;i++) {
j = scanf("%s", &names[i]);
if (!j) {
puts("Invalid!!");
return -1;
}
}

186 :デフォルトの名無しさん :2005/11/02(水) 15:24:10
#if (BUBBLE)
for (i=4;i>=0;i--)
for (j=0;j<i;j++)
if (strcmp(&names[j][0], &names[j+1][0]) > 0)
swap(names, j, j+1);
#endif

#if (QUICK)
qsort(names, 5, sizeof(Name), (int (*)(const void*, const void*))comp);
#endif

putchar('\n');
for (i=0;i<5;i++)
printf("%s\n", names[i]);
return 0;
}

void swap(Name *array, int op1, int op2)
{
Name tmp;

strcpy(tmp, array[op1]);
strcpy(array[op1], array[op2]);
strcpy(array[op2], tmp);
}

int comp(const Name* n1, const Name* n2)
{
return strcmp(n1[0], n2[0]);
}
目安箱バナー