- なあ、再帰関数好きな人いる? パート2 [転載禁止]©2ch.net
311 :デフォルトの名無しさん[sage]:2015/09/12(土) 09:25:11.15 ID:/jNm+UV1 - #include <stdio.h>
#define NUM_DATA 8 void SimSelSort(int num[ ], int n) ; void ShowData(int num[ ], int n); void main(void); /* n 個のデータの単純選択ソートを行う */ void SimSelSort(int num[ ], int n) { int i, j, k, min, temp; for (i = 0; i < n - 1; i++) { min = num[i]; /* i 番目の要素を暫定的に最小値とし */ k = i; /* 添字を保存 */ for (j = i + 1; j < n; j++) { if (num[j] < min) { /* より小さい値が現れたら */ min = num[j]; /* 最小値の入れ替え */ k = j; /* 添字を保存 */ } } /* このループを抜けるとk に最小値の添字が入っている */ temp = num[i]; /* i 番目の要素と最小値の交換 */ num[i] = num[k]; num[k] = temp; ShowData(num, NUM_DATA); } }
| - なあ、再帰関数好きな人いる? パート2 [転載禁止]©2ch.net
312 :デフォルトの名無しさん[sage]:2015/09/12(土) 09:25:44.37 ID:/jNm+UV1 - tree* ith_child(tree* v, int i, bool& b){
if(v->childsize <= i) { b = true; return v->parent; } return v->child[i]; } //ノード処理 tree* nodefunc(tree* root, tree* v) { int i = 0; bool b = false; while(!end(root, v, i, b)){ i += 1; //次のノード b = false; v = ith_child(v, i ,b); if(!b){//v:子ノード処理} else{//v:親ノード処理} } }
| - なあ、再帰関数好きな人いる? パート2 [転載禁止]©2ch.net
313 :デフォルトの名無しさん[sage]:2015/09/12(土) 09:26:00.47 ID:/jNm+UV1 - //終了検知
bool end(tree* root, tree* v, int i, bool& b){ return ((b || !v->childsize) && v == root && v->childsize <= i) } //次の順番のノードを返す tree* next(tree* v, int i, bool& b){ if(v->childsize <= i) { b = true; return v->parent; } return v->child[i]; } //ノード処理 tree* nodefunc(tree* root, tree* v) { int i = 0; bool b = false; while(!end(root, v, i, b)){ i += 1; b = false; v = next(v, i ,b); if(!b){//v:子ノード処理} else{//v:親ノード処理} } }
| - なあ、再帰関数好きな人いる? パート2 [転載禁止]©2ch.net
314 :デフォルトの名無しさん[sage]:2015/09/12(土) 09:26:32.64 ID:/jNm+UV1 - class tree{
public: tree* parent;//rootのparentはnullptr tree* chlid[];//説明の便宜上 int childsize; ... }; //終了検知 bool end(tree* root, tree* v, int i, bool& b){ return ((b || !v->childsize) && v == root && (i < 0 || v->childsize <= i)) } //iの順番のノードを返す tree* at(tree* v, int i, bool& b){ if(i < 0 || v->childsize <= i) { b = true; return v->parent; } return v->child[i]; } //ノード処理 tree* nodefunc(tree* root, tree* v) { int i = 0; bool b = false; //最初のノード処理 while(!end(root, v, i, b)){ i += 1; //次のノード b = false; v = at(v, i ,b); if(!b){//v:子ノード処理} else{//v:親ノード処理} } return v; }
| - なあ、再帰関数好きな人いる? パート2 [転載禁止]©2ch.net
315 :デフォルトの名無しさん[sage]:2015/09/12(土) 09:26:50.60 ID:/jNm+UV1 - /* n 個のデータを表示 */
void ShowData(int num[ ], int n) { while (n--) printf("%d ", *num++); printf("\n"); } void main(void) { /* ソート対象のデータ */ int num[ ] = {8, 7, 6, 5, 4, 3, 2, 1}; /* ソート前のデータの表示 */ printf("ソート前: "); ShowData(num, NUM_DATA); printf("\n"); /* ソート */ SimSelSort(num, NUM_DATA); printf("\n"); /* ソート後のデータの表示 */ printf("ソート後: "); ShowData(num, NUM_DATA); printf("\n"); }
|
|