Program Explanation
The Selection Sort algorithm is a simple comparison-based sorting algorithm. It divides the input list into two parts: a sorted part and an unsorted part. The algorithm repeatedly selects the smallest (or largest, depending on sorting order) element from the unsorted part and moves it to the end of the sorted part.
Program Structure
- Function
selectionSort
: This function takes an array and its size as parameters and sorts the array in ascending order using the Selection Sort algorithm. - Function
printArray
: This function prints the elements of the array to the console. - Function
main
: The entry point of the program. It initializes an array, calls the sorting function, and prints the sorted array.
C++ Code
#include <iostream>
using namespace std;
/**
* Function to perform selection sort on an array.
* @param arr The array to be sorted.
* @param n The number of elements in the array.
*/
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
// Find the index of the minimum element in the unsorted portion
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element
if (minIndex != i) {
swap(arr[i], arr[minIndex]);
}
}
}
/**
* Function to print the elements of an array.
* @param arr The array to be printed.
* @param n The number of elements in the array.
*/
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
/**
* The main function where the program execution begins.
*/
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
printArray(arr, n);
selectionSort(arr, n);
cout << "Sorted array: ";
printArray(arr, n);
return 0;
}
How to Compile and Run
- Copy the code into a file named
selection_sort.cpp
. - Open a terminal and navigate to the directory containing the file.
- Compile the program using the command:
g++ selection_sort.cpp -o selection_sort
. - Run the program with the command:
./selection_sort
.
Explanation of the Code:
- Function
selectionSort
: This function iterates over the array, finds the minimum element from the unsorted portion, and swaps it with the first element of the unsorted portion. - Function
printArray
: This function is used to display the elements of the array on the console. - Function
main
: It initializes an example array, prints the original array, calls theselectionSort
function to sort it, and then prints the sorted array.