I am having trouble with segmentation error with sorting code. I have tried to understand how I am accessing something that is out of boundaries, but so far no ideas. It runs smoothly in cases where the needle is in the haystack, but fails when it isn't. What is weird about it is that the following code prints all the values (values[996:999]) at the end of the sort code, but fails to print the "Done that" phrase. Checked the sorted values and they are correct. Having no idea why I am accessing memory after that. I am using pointers for swap.
Any help would be appreciated. Snippet of the code:
printf("%d\n", values[995]);
printf("%d\n", values[996]);
printf("%d\n", values[997]);
printf("%d\n", values[998]);
printf("%d\n", values[999]);
printf("Done that");
return;
}
void swap(int *a,int *b)
{
int position = *a;
*a = *b;
*b = position;
}
Added requested code:
void sort(int values[], int n)
{
// TODO: implement an O(n^2) sorting algorithm
for(int i = 0; i < n-1; i++){
int min = i;
for(int j = i+1; j < n; j++){
if(values[min] > values[j]){
min = j;
}
}
if(values[i] > values[min]){
swap(&values[i],&values[min]);
}
}
printf("%d\n", values[995]);
printf("%d\n", }values[996]);
printf("%d\n", values[997]);
printf("%d\n", values[998]);
printf("%d\n", values[999]);
printf("Done that");
return;
}