0004. 選択ソート(C言語)

戻る

selsort.cのソースコード】


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N 100

void selsort(int a[], int top, int end);

int main(void)
{
	int i, a[N];
	
	srand((unsigned int)time(NULL));
	
	printf("【整列前】\n");
	for (i = 0; i < N; i++) {
		a[i] = rand();
		printf("%6d ", a[i]);
		if ((i + 1) % 10 == 0)
			printf("\n");
	}
	printf("\n");
	
	selsort(a, 0, N - 1);
	
	printf("【整列後】\n");
	for (i = 0; i < N; i++) {
		printf("%6d ", a[i]);
		if ((i + 1) % 10 == 0)
			printf("\n");
	}
	
	return EXIT_SUCCESS;
}

void selsort(int a[], int top, int end)
{
	int i, j, tmp, pos;
	
	for (i = top; i < end; i++) {
		pos = i;
		for (j = i + 1; j <= end; j++)
			if (a[j] < a[pos])
				pos = j;
		tmp = a[i]; a[i] = a[pos]; a[pos] = tmp;
	}
}


selsortの実行結果】赤字はキーボードからの入力を表す。

D:\test>selsort
【整列前】
 11120  27853  19451  27671   7293  15367  25189  23240  32731  13281
  1088   2880   5524  16776   8719  17351    875  18953  18877  25446
 20938    881  11060   9271  13564  26930  19243  21215  30364  20425
 22591   8024   4942  23454  22086  27380  24749  24364   5088  14238
 20356  25697   7758   7267   7744  25928  10120  25394   4005  30693
  4745  13280  31169  29025   6638  28783  16670  17511  17599   9872
  5180   7885   7565  14950  31550   2679  24509  11917   4068   5496
  3875  11611  29113  17787  11731  14182  19086  23138   1075   6982
 30502   9260  12117   6812  10291  28700  27012  24659   3969  20759
 16669  11301  28018  18255  12705  22369   4778   2846  21255   5868

【整列後】
   875    881   1075   1088   2679   2846   2880   3875   3969   4005
  4068   4745   4778   4942   5088   5180   5496   5524   5868   6638
  6812   6982   7267   7293   7565   7744   7758   7885   8024   8719
  9260   9271   9872  10120  10291  11060  11120  11301  11611  11731
 11917  12117  12705  13280  13281  13564  14182  14238  14950  15367
 16669  16670  16776  17351  17511  17599  17787  18255  18877  18953
 19086  19243  19451  20356  20425  20759  20938  21215  21255  22086
 22369  22591  23138  23240  23454  24364  24509  24659  24749  25189
 25394  25446  25697  25928  26930  27012  27380  27671  27853  28018
 28700  28783  29025  29113  30364  30502  30693  31169  31550  32731

参考文献
・林晴比古著、「C言語による実用アルゴリズム入門」、ソフトバンク・パブリッシング(株)・2004年発行。
・玉井浩著、「新・演習と応用 プログラミング言語=1 演習と応用C」、(株)サイエンス社・1999年発行。
戻る