/***************************************************************
* Name: Prof. Orta
* Course: Computer Science & Programming
* Class: CS04103 Section: 1 & 2
* Assignment Date: 10/27/20
* File Name: selectionSort
*****************************************************************
* ID: 001
* Purpose: Explain Selection Sort in in C++
*****************************************************************/
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
using namespace std;
void selectionSort(int [], int);
int main() {
const int SIZE = 10;
int numbers[SIZE];
// Seed for random number generation
srand(std::time(0));
// Fill the array with random numbers between 1 and 100
for (int i = 0; i < SIZE; ++i) {
numbers[i] = rand() % 10 + 1;
}
cout << "Original array: ";
for (int i = 0; i < SIZE; ++i) {
cout << numbers[i] << " ";
}
cout << endl;
// Sort the array
selectionSort(numbers, SIZE);
cout << "Sorted array: ";
for (int i = 0; i < SIZE; ++i) {
cout << numbers[i] << " ";
}
cout << endl;
return 0;
}
void selectionSort(int arr[], int size) {
for (int i = 0; i < size - 1; ++i) {
int minIndex = i;
// Find the index of the smallest element in the remaining array
for (int j = i + 1; j < size; ++j) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap if a smaller element was found
if (minIndex != i) {
swap(arr[i], arr[minIndex]);
}
}
}