Majd
Majd

Reputation: 348

Array sorting in c by reference

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.

Upvotes: 0

Views: 1305

Answers (2)

user3629249
user3629249

Reputation: 16540

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]); 
           }
       }
    }
} 

Upvotes: 0

dbush
dbush

Reputation: 223992

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++){

Upvotes: 2

Related Questions