Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created April 9, 2020 21:53
Show Gist options
  • Save misterpoloy/ccb22f069050e3bfbef1732234f09b14 to your computer and use it in GitHub Desktop.
Save misterpoloy/ccb22f069050e3bfbef1732234f09b14 to your computer and use it in GitHub Desktop.
Selection Sort in cpp
#include <iostream>
void selectionSort(int* myList, int length) {
for (int i = 0; i < length - 1; i++) { // Actually is ok only n -2
int indexMin = i; // ith position: elements from i till n-1 are candidates
for (int j = i + 1; j < length; j++) { // Analizo el siguiente
if (myList[j] < myList[indexMin]) {
indexMin = j; // update the index of minimun element
}
}
int temp = myList[i];
myList[i] = myList[indexMin];
myList[indexMin] = temp;
}
}
int main() {
int myList[] {
5,
3,
1,
4,
2
};
selectionSort(myList, 5);
for (int n : myList) {
std::cout << n << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment