Last active
August 29, 2015 14:15
-
-
Save rcanepa/4a5e563a0e82780c8459 to your computer and use it in GitHub Desktop.
C++ Selection Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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