はじめての C

7月11日分の 日記が まちがっていたので、削除しました。 訂正分は 次のとおりです。


以前 つくった クイックソートプログラムを 元にして、シェルソートの コードを 書いてみる。
http://www4.kcn.ne.jp/~yoitiro/hatena/knr2nd_4.txt
はじめに shell_sort ファイル


/* shell_sort.c */
#include

void insertion_sort();

void shell_sort(int *list, int n)
{
int h = 1;
for ( ; h <= n / 9; h = 3 * h + 1)
;
for ( ; h > 0; h /= 3)
insertion_sort(list, h, n);
}

void insertion_sort(int *list, int left, int right)
{
int step, i;
int temp;

for (step = left; step < right; step++) {
temp = list[step];
for (i = step; i >= left; i -= left)
if (temp < list[i - left])
list[i] = list[i - left];
else
break;
list[i] = temp;
}
}

read_array2 と print_array2

/* read_array2.c */
#include

int read_array2(int a[], int limit)
{
int n = 0;
while (n < limit && scanf("%d", &a[n]) != EOF)
++n;
return n;
}


/* print_array2.c */
#include

void print_array2(int a[], int n)
{
int i;
for (i = 0; i < n; i++) {
printf("%3d ", a[i]);
if ((i + 1) % 10 == 0)
putchar('\n');
}
if (1 % 10 != 0)
putchar('\n');
}

次が main ファイル

/* s_main.c */
#include
#include "s_header.h"

main()
{
int *list;
int n;

n = read_array2(list, MAX);
shell_sort(list, n);
print_array2(list, n);

return 0;
}

ヘッダファイルも

/*s_header.h */
#define MAX 100

int read_array2();
int print_array2();
void shell_sort();

read_array2 と print_array2 では、仮引数が 配列に なってますが この場合、ポインタを 使って 渡しています。
あとは コンパイルして、クイックソートのときと 同じく、random プログラムを 使って 確認します。

$cc -c s_main.c shell_sort.c read_array2.c print_array2.c
$cc -o s_sort s_main.o shell_sort.o read_array2.o print_array2.o

$./random
$./s_sort < random.txt

(追記) クイックソートと、入出力のところが 違ってました。 あと、細かいミスも いろいろと ... oLr