Skip to content

Instantly share code, notes, and snippets.

@rcanepa
Last active August 29, 2015 14:15
Show Gist options
  • Save rcanepa/4a5e563a0e82780c8459 to your computer and use it in GitHub Desktop.
Save rcanepa/4a5e563a0e82780c8459 to your computer and use it in GitHub Desktop.
C++ Selection Sort
#include <iostream>
#include <stdlib.h>
void selection_sort(int *list, int list_length);
int main()
{
int list_length = 30;
int list[list_length];
/* Creates a random int list */
srand(time(NULL));
for (int i = 0; i < list_length; i++)
{
list[i] = rand() % 300;
std::cout << i << ":" << list[i] << std::endl;
}
selection_sort(list, list_length);
/* Check the result */
for (int k = 0; k < list_length; k++){
std::cout << list[k] << ",";
}
return 0;
}
void selection_sort(int *list, int list_length)
{
int min_pos;
int temp;
for (int i = 0; i < list_length; i++)
{
min_pos = i;
for (int j = i + 1; j < list_length; j++)
{
if (list[j] <= list[min_pos])
{
min_pos = j;
}
}
temp = list[i];
list[i] = list[min_pos];
list[min_pos] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment