Code for Selection Sort
// Program for Selection Sort
#include <bits/stdc++.h>
using namespace std;
//Swap function
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{
// Finding the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swapping the minimum found element with first element
if(min_idx!=i)
swap(&arr[min_idx], &arr[i]);
}
}
//Function for printing an array
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Main program for Output
int main()
{
int arr[] = {30, 15, 10, 20, 6};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
}
So the Final Output Will be: 6 10 15 20 30
6
