#include<bits/stdc++.h>
using namespace std;
int main(){
//selection sort
int a[5] = {54,69,12,2,89};
//find minimum in rest of the array and swap with the current index;
//if(n>1)
for(int i=0;i<5-1;i++)
{
int minloc = i;
for(int j=i+1;j<5;j++)
{
if(a[minloc]>a[j])
{
minloc = j;
}
}
swap(a[i],a[minloc]);
}
for(int i=0;i<5;i++)
{
cout<<a[i]<<" ";
}
return 0;
}
class Practice
{
public:
void practice1(vector<int> &arr)
{
/* Selection sorting */
int current_min_i = 0;
for (int i = 0; i < arr.size() - 1; i++)
{
current_min_i = i;
for (int j = i + 1; j < arr.size(); j++)
if (arr[current_min_i] > arr[j])
current_min_i = j;
swap(arr[i], arr[current_min_i]);
}
cout << "Displaying sorted array: ";
for (int i : arr)
cout << i << " ";
}
};
int main()
{
vector<int> arr{64, 25, 12, 22, 11};
Practice op;
op.practice1(arr);
}
//Selection sort algorithm
selectionSort(array, size)
repeat (size - 1) times
set the first unsorted element as the minimum
for each of the unsorted elements
if element < currentMinimum
set element as new minimum
swap minimum with first unsorted position
end selectionSort
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void Tri_Selection(int tab[],int n)
{
for (int i=0; i<n; i++)
{
for (int j=i+1; j<n; j++)
if (tab[i] > tab[j])
swap(tab[i],tab[j]);
}
}
#include <iostream>
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n) {
int i, j, min_idx;
for (i = 0; i < n - 1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
if (min_idx != i) {
swap(&arr[min_idx], &arr[i]);
}
}
}
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
std::cout << "unsorted array: ";
printArray(arr, n);
std::cout << std::endl;
selectionSort(arr, n);
std::cout << "Sorted array: ";
printArray(arr, n);
std::cout << std::endl;
return EXIT_SUCCESS;
}