selection sort c++ algorithm
Selection Sort Algorithm in C++
The selection sort algorithm is a simple comparison-based sorting algorithm. It works by dividing the input array into two parts: the sorted part and the unsorted part. In each iteration, it selects the smallest (or largest) element from the unsorted part and moves it to the sorted part.
Here is the step-by-step explanation of the selection sort algorithm in C++:
Start with an unsorted array
arr
of sizen
.Iterate through the array from the first element
i = 0
toi = n-1
.Set
minIndex
as the index of the minimum element in the unsorted part (i
ton-1
).Iterate through the unsorted part of the array from
j = i+1
toj = n-1
.If
arr[j]
is less thanarr[minIndex]
, updateminIndex
toj
.After the inner loop, swap the minimum element (
arr[minIndex]
) with the current element (arr[i]
).Repeat steps 2 to 6 until the array is completely sorted.
The array is now sorted in ascending order.
C++ Code Example:
#include <iostream>
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;
}
}
std::swap(arr[i], arr[minIndex]);
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
std::cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
This code snippet demonstrates the implementation of the selection sort algorithm in C++. The selectionSort
function takes an array arr
and its size n
as parameters. It performs the selection sort algorithm and sorts the array in ascending order. The main
function initializes an array, calls the selectionSort
function, and prints the sorted array.