ファイルから文字列を読み込んで辞書順にヒープソートするソースですが動きません。go,copy,hop,
,agoと4つの単語が一行に1つづつ書かれているファイルでは実行するとgo,copy,hopの3つだけが表示されます。
どこがいけないでしょうか?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void swap( char *a, char *b );
void Hpsort(char s[/url], int n);
void DownHeap(char s[/url], int leaf, int root);
void swap( char *a, char *b )
{
char tmp;
// 文字列の入れ替え
while ( (*a != '\0') && (*b != '\0') ){
tmp = *a;
*a = *b;
*b = tmp;
a++;
b++;
}
// a 文字列が長い場合
while ( *a != '\0' ){
*b++ = *a; *a++ = '\0';
}
// b 文字列が長い場合
while ( *b != '\0' ){
*a++ = *b; *b++ = '\0';
}
*a = '\0';
*b = '\0';
}
void Hpsort(char s[/url], int n)
{
int leaf, root;
leaf = n; /* 初期値は末尾の要素 */
root = n/2; /* 初期値はその親 */
while (root > 0 ) { /* 半順序木を構成 */
DownHeap(s, leaf, root);
root--;
}
while(leaf > 0) {
swap(&s[1], &s[leaf]); /* 半順序木の根と末尾の要素を交換 */
leaf--; /* 末尾の要素を半順序木から外す */
DownHeap(s, leaf, 1); /* 半順序木を再構成する */
}
}
void DownHeap(char s[/url], int leaf, int root)
{
int i;
i = root * 2;
while (i <= leaf) {
if (i < leaf &&strcmp(&s[i + 1] , &s)>0) /* a と a[i + 1] の大きい方と */
i++;
if (strcmp(&s[root], &s)>0) /* a[root] と比較 */
break; /* 子の方が大きければ */
swap(&s[root], &s); /* 交換 */
root = i; /* 更にその子についても調べる */
i = root * 2;
}
}
int main(){
int i;
FILE *fp;
char s[4][10];
fp=fopen("test.txt","r");
if(fp==NULL){
printf("file not found\n");
exit(0);
}
for(i=1;i<5;i++){
fgets(s,10,fp);
}
for(i=1;i<5;i++){
printf("%s",s);
}
Hpsort(s[4],4);
for(i=1;i<5;i++){
printf("%s",s);
}
fclose(fp);
}