Created
December 23, 2017 04:31
-
-
Save komasaru/d1d096c949c8b6904174ff39693f3ca6 to your computer and use it in GitHub Desktop.
C++ source code to generate a heap with the upward method.
This file contains 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
/*********************************************************** | |
* ヒープ生成(上方移動) | |
**********************************************************/ | |
#include <cstdlib> // for srand() | |
#include <iostream> // for cout | |
#include <stdio.h> // for printf() | |
#define N 100 // データ個数 | |
using namespace std; | |
/* | |
* ヒープクラス | |
*/ | |
class Heap | |
{ | |
// 各種変数 | |
int n, i, s, p, w; // Loop インデックス等 | |
int base[N]; // 元データ用配列 | |
int heap[N + 1]; // ヒープ用配列 | |
public: | |
Heap(); // コンストラクタ | |
void generate(); // ヒープ生成 | |
}; | |
/* | |
* コンストラクタ | |
*/ | |
Heap::Heap() | |
{ | |
// ヒープに追加する要素の配列を生成 | |
srand((unsigned int)time(NULL)); | |
printf("#### Base\n"); | |
for (i = 0; i < N; i++) { | |
base[i] = rand() % N + 1; | |
printf("%5d ", base[i]); | |
if ((i + 1) % 10 == 0) printf("\n"); | |
} | |
printf("\n"); | |
} | |
/* | |
* ヒープ生成 | |
*/ | |
void Heap::generate() | |
{ | |
for (n = 1; n <= N; n++) { | |
// 元データ配列から1つヒープ要素として追加 | |
heap[n] = base[n - 1]; | |
s = n; // 追加要素の位置 | |
p = s / 2; // 親要素の位置 | |
while (s >= 2 && heap[p] > heap[s]) { | |
w = heap[p]; | |
heap[p] = heap[s]; | |
heap[s] = w; | |
s = p; // 追加要素の位置 | |
p = s / 2; // 親要素の位置 | |
} | |
} | |
// 結果出力 | |
printf("#### Heap\n"); | |
for (n = 1; n <= N; n++) { | |
printf("%5d ", heap[n]); | |
if (n % 10 == 0) printf("\n"); | |
} | |
printf("\n"); | |
} | |
/* | |
* メイン処理 | |
*/ | |
int main() | |
{ | |
try | |
{ | |
// ==== インスタンス化 | |
Heap objHeap; | |
// ==== ヒープ生成 | |
objHeap.generate(); | |
} | |
catch (...) { | |
// ==== 異常終了 | |
cout << "例外発生!" << endl; | |
return -1; | |
} | |
// ==== 正常終了 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment