====== swap関数と関数スコープ ======
#include
#include
using namespace std;
//ソーティング
//選択ソートを実装することを考える
//アルゴリズムを考えて→アルゴリズムの完成
//アルゴリズム→プログラム=ソースコードに直す作業
// :実装(implement いんぷりめんと) インプリメントする
//昇順 データの中で一番小さいものを探してくる
//未ソート配列の左端と最小値のデータを交換
// 3 1 4 2
//0 1|3 4 2
//1 1 2|4 3
//2 1 2 3|4
//3 1 2 3 4|
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
void swap(int &a, int &b) //参照渡し 参照を渡している
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
int main()
{
//かき混ぜの魔法
shuffle(arr, arr+10, default_random_engine());
for (int i = 0; i < 10; i++)
cout << arr[i] << " ";
swap(arr[0], arr[1]);
//ソートの実行
//sort(arr, arr + 10);
cout << endl;
for (int i = 0; i < 10; i++)
cout << arr[i] << " ";
return 0;
}
==== ソートアルゴリズムに応用 ====
これを、ループ実行出来たらソートできるんじゃない?\\
0 indexが0~9のうちの最小値を求める→index返す
swap(0, index)
1 indexが1~9のうちの最小値を求める→index返す
swap(1, index)
2 indexが2~9のうちの最小値を求める→index返す
swap(2, index)
3 indexが3~9のうちの最小値を求める→index返す
swap(3, index)
4 indexが4~9のうちの最小値を求める→index返す
swap(4, index)
5 indexが5~9のうちの最小値を求める→index返す
swap(5, index)
6 indexが6~9のうちの最小値を求める→index返す
swap(6, index)
6 indexが7~9のうちの最小値を求める→index返す
swap(7, index)
8 indexが8~9のうちの最小値を求める→index返す
swap(8, index)