Last active
May 29, 2018 13:59
-
-
Save KeitetsuWorks/35de7832e13c302170b5669ea4a1b74b to your computer and use it in GitHub Desktop.
配列に5個の数値を格納し、最大値を使って小さい順(昇順)に並び替えるプログラム
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file q10175221270.c | |
* @brief 配列に5個の数値を格納し、最大値を使って小さい順(昇順)に並び替える | |
* @author Keitetsu | |
* @date 2017/06/11 | |
* @copyright Copyright (c) 2017 Keitetsu | |
* @par License | |
* This software is released under the MIT License. | |
*/ | |
#include <stdio.h> | |
#define DATA_NUM 5 /**< ソート対象データの数 */ | |
int main(void) | |
{ | |
int data[DATA_NUM]; | |
int i, j, max; | |
int data_tmp; | |
for (i = 0; i < DATA_NUM; i++) { | |
printf("%2d/%2d個目の数値を入力: ", i + 1, DATA_NUM); | |
scanf("%d", &data[i]); | |
} | |
/* 昇順選択ソート */ | |
for (i = (DATA_NUM - 1); i >= 1; i--) { | |
max = i; /* 最大値の初期インデックス */ | |
for (j = (i - 1); j >= 0; j--) { | |
if (data[j] > data[max]) { /* より大きい値が発見された場合 */ | |
max = j; /* 最大値のインデックスを更新*/ | |
} | |
} | |
if (max != i) { /* 最大値のインデックスが更新されていた場合 */ | |
data_tmp = data[i]; /* データのスワップ */ | |
data[i] = data[max]; | |
data[max] = data_tmp; | |
} | |
} | |
printf("昇順ソート結果: \n"); | |
for (i = 0; i < DATA_NUM; i++) { | |
printf("%2d/%2d個目の数値: %d\n", i + 1, DATA_NUM, data[i]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment