#include <iostream>
int main() {
int values[] = {3, 1, 2};
int i = 0;
while (i < 2) {
int smallest = i;
int j = i + 1;
while (j < 3) {
if (values[j] < values[smallest]) {
smallest = j;
}
j += 1;
}
int saved = values[i];
values[i] = values[smallest];
values[smallest] = saved;
i += 1;
}
i = 0;
while (i < 3) {
std::cout << values[i] << '\n';
i += 1;
}
}
#include <iostream>
using namespace std;
class SelectionSortExample
{
// Access specifier
public:
void selectionSort(int arr[], size_t size) {
for(size_t i = 0; i < size - 1; i++) {
int minIndex = i;
for(size_t j = i + 1; j < size; j++) {
if(arr[minIndex] > arr[j]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
void printArray(const int arr[], size_t size) {
for(size_t i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
};
int main(int argc, const char * argv[])
{
// Declare an object of class geeks
SelectionSortExample obj;
int arr[] = { 15, 3, 12, 6, -9, 9, 0 };
const size_t SIZE = sizeof(arr) / sizeof(*arr);
cout << "Before Sorting: ";
obj.printArray(arr, SIZE);
obj.selectionSort(arr, SIZE);
cout << "After Sorting: ";
obj.printArray(arr, SIZE);
return 0;
}
出力
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
広告
例を順に追ってみよう
[15, 3, 12, 6, -9, 9, 0] から始めます。
添字0から始めます。残りの値を調べて、最小値(−9)がどの位置にあるかを覚えておきます。
−9と先頭の値15を入れ替えます。これで先頭の位置が確定しました。
次の位置から同じ手順を繰り返します。一つだけ残った時点で、配列全体の並べ替えが終わっています。
C++ の選択ソートを順に解説
C++ のソースコード
#include <iostream>
using namespace std;
class SelectionSortExample
{
// Access specifier
public:
void selectionSort(int arr[], size_t size) {
// Loop all the element in an array except the last element
for(size_t i = 0; i < size - 1; i++) {
int minIndex = i;
// Find an index of a lowest element in the right-hand side
// corresponding to the element arr[i].
for(size_t j = i + 1; j < size; j++) {
if(arr[minIndex] > arr[j]) {
minIndex = j;
}
}
// Swap the lowest element with the current element (i.e. arr[i] <=> arr[minIndex])
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
void printArray(const int arr[], size_t size) {
// Loop the item and print each item in the console with white space seperated
for(size_t i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
};
int main(int argc, const char * argv[])
{
// Declare an object of class geeks
SelectionSortExample obj;
int arr[] = { 15, 3, 12, 6, -9, 9, 0 };
const size_t SIZE = sizeof(arr) / sizeof(*arr);
cout << "Before Sorting: ";
obj.printArray(arr, SIZE);
obj.selectionSort(arr, SIZE);
cout << "After Sorting: ";
obj.printArray(arr, SIZE);
return 0;
}
出力
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15