I have to code a function to sort an integer array in C:
The Code:
// the function:
void my_sort_intarr(int *array, int size){
int tmp;
int sorted = 1;
while(sorted == 1){
sorted = 0;
for (int i = 0 ; i < size ; i++){
if(array[i] > array[i+1]){
tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
sorted = 1;
}
if (array[i] == array[i+1]){
continue;
}
}
}
}
// My Main
void my_sort_intarr(int *array, int size);
int main(){
int arr[7] = {9, 4, 8, 2, 3, 3, 9};
my_sort_intarr( arr, 7);
for (int i = 0; i < 7; i++){
printf("%d\n", arr[i]);
}
return 0;
}
when testing this I'm getting the result: 0 2 3 3 4 8 9 I want to know where the 0 is coming from and how to do this right.
You're going off the end of the array:
for (int i = 0 ; i < size ; i++){
if(array[i] > array[i+1]){
When i
is size-1
, array[i+1]
is one element past the end of the array. Reading or writing past the bounds of an array triggers undefined behavior, which in this case manifests as a 0
element showing up in the list.
Change your loop condition to:
for (int i = 0 ; i < size - 1 ; i++){