Reputation: 99
I have this assignment for my C class. She gave us pseudo code for the selection sort. There's some other requisites, but those I don't need help with. I followed her code, and even looked online for sample code. And mine follows the same concept but it never works. When I print the "sorted" array, it prints the unsorted numbers and a bunch of other numbers. If I enter '8 7 6 5 4 3 2 1' my array prints '8765432146142368001234567846142368'.
#define MAXSIZE 10
void print_array(const int a[], int size);
int main()
{
int get_numbers(int n[]); //Function to retrieve a list of numbers and
returns an array of the numbers
int numbers[MAXSIZE]; //Array to store unsorted list of numbers
void selection_sort(int a[], int size);
puts("Enter each number then press enter. (Ctrl + Z) to end.");
get_numbers(numbers);
selection_sort(numbers, MAXSIZE);
print_array(numbers, MAXSIZE);
}
void get_numbers(int n[])
{
int s; //Stores return value of scanf
int i; //Stores amount of values entered
for(i = 0; (s = scanf("%i", &n[i])) != EOF; i++);
if(i == 0)
{
puts("Error: No numbers entered.");
}else if(i > MAXSIZE)
{
puts("Error: Too many values entered.");
print_array(n, MAXSIZE);
}else
{
print_array(n, MAXSIZE);
}
}
void print_array(const int a[], int size)
{
for(int i = 0; i < size; i++)
{
printf("%i", a[i]);
}
}
void selection_sort(int a[], int size)
{
void swap(int n[], int i, int min_index);
for(int i = 0; i < (size - 1); i++)
{
int min = a[i];
int min_index = i;
for(int j = (i + 1); j < size; j++)
{
if(a[j] < min)
{
min = a[j];
min_index = j;
}
}
swap(a, i, min_index);
}
}
void swap(int n[], int i, int min_index)
{
int temp = n[i];
n[i] = n[min_index];
n[min_index] = temp;
}
Upvotes: 0
Views: 59
Reputation: 99
Thank you for everyone and their tips! I took what Bob Jarvis had mentioned (sorting based on exact number of values, spacing my output). My main problem was that it seemed to be printing a bunch of random numbers which I was unsure where it came from. After spacing I realized it does sort them but there was a random number ex. 8 7 6 5 4 3 2 1 44176288 0 1 2 3 4 5 6 7 8 44176288 0. After some more debugging I realized that I was also printing not at exact array size. After fixing all the different sizes it was fixed.
Upvotes: 0
Reputation: 78
There are quite a few issues with your program.
Function prototypes need to be declared before any other functions.
If they bail out early/late, you need to pass the value of i to print_array. If you pass MAXSIZE you will be reading/writing to memory that isn't yours. Which is why you get weird values.
Upvotes: 1