0

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.

1
  • 2
    On the last iteration of the for loop, array[i+1] is outside the array. Commented Mar 17, 2021 at 23:16

2 Answers 2

2

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++){
Sign up to request clarification or add additional context in comments.

1 Comment

i feel so embarrased right now; thank you, accepting answer in 7 mins
0

The OPs posted code is not a valid sorting algorithm. I.E. the result will not always sort the list of int elements, especially if a small element is toward the end of the list.

sorting algorithms

Suggest the (simple but slow as number of elements increases) Bubble Sort

The bubble sort algorithm:

void swap(int *xp, int *yp) 
{ 
    int temp = *xp; 
    *xp = *yp; 
    *yp = temp; 
} 

// A function to implement bubble sort 
void bubbleSort(int arr[], int n) 
{ 
   for ( int i = 0; i < n-1; i++) 
   {      
       // Last i elements are already in place    
       for ( int j = 0; j < n-i-1; j++) 
       { 
           if (arr[j] > arr[j+1]) 
           {
               swap(&arr[j], &arr[j+1]); 
           }
       }
    }
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.