I'm having a problem with my code that deals with selection sort...
For some reason it works for some examples, but it does not work for others, check below:
It satisfies some test examples...This is the example the professor gave us...
6, 3, 7, 86, 2 ----> output is 2, 3, 6, 7, 86 (So this works)
But some other test examples don't work and some do like
100, 2, 24, 86, 1 -----> output is 1, 2, 86, 24, 100 (does not work)
-30, 5, 23, -2, 100, -65 ----> output is -65, -30, -2, 5, 23, 100 (works)
-100, 65, 2, -42, 16 -----> output is -100, 2, 16, -42, 65 (does not work)
So I cannot see where there is a problem in my code. It seems like it is sort of random...
Code:
#include<stdio.h>
#define N 20
void sort(int* const p, int len);
void swap(int* const p, int a, int b);
void sort(int* const p, int len)
{
int i, x, y, index_of_min;
for(x=0; x<len; x++)
{
index_of_min = x;
for(y=x; y<len; y++)
{
if(*(p+index_of_min) > *(p+y))
index_of_min = y;
swap(p, x, index_of_min);
}
}
printf("\nThe sorted elements of array are:\n");
for(i=0; i<len; i++)
{
printf("%d, ", *(p+i));
}
}
void swap(int* const p, int x, int index_of_min)
{
int temp;
temp = *(p+x);
*(p+x) = *(p + index_of_min);
*(p + index_of_min) = temp;
}
int main(void)
{
int i, length;
int array[N] = {0};
printf("\nInput the length of array: ");
scanf("%d", &length);
printf("Input the elements of array\n");
for(i=0; i< length; i++)
{
printf("\nElement %d: ", i);
scanf("%d", &array[i]);
}
printf("\nThe input elements of the array are:\n");
for(i=0; i< length; i++)
{
printf("%d", array[i]);
printf(", ");
}
sort(array, length);
printf("\n\n");
return(0);
}
Thanks
Also, the assignment calls for the index address of the pointers not be modified thus that is why the parameters in the functions are the way they are: int* const p