Group
Search and Sort Algorithms in C++
Objective
Create a function called selectionSort that takes an integer array and its size as parameters. Implement the logic to find the minimum element in each pass and swap it with the current element. In the main function, define an unsorted array, apply the selectionSort function to sort it, and then print the sorted array.
Write a function that sorts an array using the selection sort algorithm.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include input-output stream library
using namespace std;
// Function to perform selection sort
void selectionSort(int arr[], int n) {
// Traverse the entire array
for (int i = 0; i < n - 1; i++) {
int minIndex = i; // Assume the current index has the smallest value
// Search for the smallest element in the unsorted part
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j; // Update index if smaller element is found
}
}
// Swap the found minimum element with the first unsorted element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
// Main function
int main() {
// Define an unsorted array
int arr[] = {29, 10, 14, 37, 13};
int size = sizeof(arr) / sizeof(arr[0]); // Calculate the array size
// Call the selectionSort function to sort the array
selectionSort(arr, size);
// Print the sorted array
cout << "Sorted array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0; // End of program
}
Output
Sorted array: 10 13 14 29 37