Time Complexity: O(N2)
// of Selection sort
#include <bits/stdc++.h>
using namespace std;
// A function to implement Selection sort
void selection_sort(int A[], int n)
{
int min, temp;
for (int i = 0; i < n - 1; i++)
{
min = i;
for (int j = i + 1; j < n; j++)
{
if (A[j] < A[min])
{ // finds the min element
min = j;
}
if (min!= i)
{
temp = A[i];
A[i] = A[min];
A[min] = temp;
}
}
// putting min element on its proper position.
// swap(A[min], A[i]);
}
}
// Driver code
int main()
{
int arr[] = { 9,13,15,11,2};
int N = 5;
selection_sort(arr, N);
cout << "Sorted array: ";
for (int i = 0; i < N; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
Output:
Sorted array: 2 9 11 13 15
0 Comments