c++ code for selection sort
#include <iostream>
using namespace std;
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
swap(arr[i], arr[minIndex]);
}
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted array: \n";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
Explanation: - The selectionSort function takes an array and its size as parameters. - It iterates through the array and finds the index of the minimum element in the unsorted portion of the array. - It then swaps the minimum element with the first unsorted element. - This process is repeated until the entire array is sorted. - In the main function, an array is initialized, and selectionSort is called to sort the array. - The sorted array is then printed to the console.