Skip to content

Instantly share code, notes, and snippets.

@piusayowale
Created January 22, 2022 10:33
Show Gist options
  • Save piusayowale/b357e80d0391a8f7da53497b4c283683 to your computer and use it in GitHub Desktop.
Save piusayowale/b357e80d0391a8f7da53497b4c283683 to your computer and use it in GitHub Desktop.
C++ implementation of selection sort
#include <iostream>
int findSmallestIndex(int* arr, int index, int len) {
int smallestIdx = index;
int counter = index;
while (counter < len)
{
if (arr[smallestIdx] > arr[counter]) {
smallestIdx = counter;
}
counter++;
}
return smallestIdx;
}
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
return;
}
void sort(int* arr, int len) {
int index = 0;
int smallest;
while (index < len)
{
smallest = findSmallestIndex(arr, index, len);
swap(&arr[index], &arr[smallest]);
index++;
}
}
void print(int* arr, int len) {
int index = 0;
while (index < len)
{
std::cout << arr[index] << " ";
index++;
}
std::cout << "\n";
}
int main() {
int arr[] = { 9, 0, 3, 5, -1, 2, 4, 8 };
sort(arr, 8);
print(arr, 8);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment