src/headers/selection.h
#ifndef SELECTIONSORT #define SELECTIONSORT #include <strings.h> #include <stdio.h> char** ssort(const unsigned int count, char** values); unsigned int findSmallest(const unsigned int items, char** values); char** swapValues(const unsigned int from, const unsigned int to, char** values); void printList(const unsigned int idx, const unsigned int count, char** values); #endif
src/selection.c
#include <selection.h> /* * This method will sort the list of items that it is given using the simple * selection sort, very similar to the insert sort except it will 'select' * the highest value rather than insert the value where it best fits. */ char** ssort(const unsigned int count, char** values) { unsigned int i, j; printf("sorting a list of %i values", count); for(i = 0; i < count - 1; i++) { printList(i, count, values); swapValues(findSmallest(count - i, &values[i]), 0, &values[i]); } printf("\nsorting %i items required %i selects", count, count - 1); return values; } void printList(const unsigned int idx, const unsigned int count, char** values) { unsigned int j; printf("\n%i:\tcurrent list: ", idx); for(j = 0; j < count - 1; j++) { printf("%s, ", values[j]); } printf("%s", values[j]); } unsigned int findSmallest(const unsigned int items, char** values) { char* tmp; unsigned int i, chosen = 0; for(i = 0; i < items; i++) { if(strcmp(values[chosen], values[i]) > 0) { chosen = i; } } printf(" : smallest value %s, %i comparisons", values[chosen], items); return chosen; } char** swapValues(const unsigned int from, const unsigned int to, char** values) { char* tmp = values[to]; values[to] = values[from]; values[from] = tmp; return values; }
No comments:
Post a Comment