Skip to content

Instantly share code, notes, and snippets.

@theArjun
Last active May 7, 2019 09:06
Show Gist options
  • Select an option

  • Save theArjun/704dfda0db9e60bbf92a6b5b441e58fe to your computer and use it in GitHub Desktop.

Select an option

Save theArjun/704dfda0db9e60bbf92a6b5b441e58fe to your computer and use it in GitHub Desktop.
Selection Sort in C++
#include <iostream>
using namespace std;
void selection_sort(int arr[], int size)
{
for (int i = 0; i < size - 1; i++)
{
// Let's suppose the index i to be the index of minimum in the array.
int index_of_minimum = i;
// Nested for loop checks the index of minimum number in the array, and stores in index_of_minimum.
for (int j = i + 1; j < size - 1; j++)
{
if (arr[j] < arr[index_of_minimum])
{
index_of_minimum = j;
}
}
// If arr[i] is same as the arr[index_of_minimum], then no need to swap.
// This condition may arise if the array has duplicate elements.
if (arr[i] != arr[index_of_minimum])
{
int temp = arr[i];
arr[i] = arr[index_of_minimum];
arr[index_of_minimum] = temp;
}
cout << "\nPass " << i + 1 << " : ";
for (int i = 0; i < size - 1; i++)
{
cout << arr[i] << " ";
}
}
}
int main()
{
int arr[] = {1, 9, 2, 8, 4, 7, 5, 6, 7};
int size = sizeof(arr) / sizeof(arr[0]);
selection_sort(arr, size);
cout << "\nSorted Elements : ";
for (int i = 0; i < size - 1; i++)
{
cout << arr[i] << " ";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment