Sam Fischer
Sam Fischer

Reputation: 19

What's going wrong with this C sort array function?

Here's my code for a function that will sort an array passed in as a pointer :

#include <stdlib.h>
#include <stdio.h>

void sortArray(int * numbers, unsigned int n, unsigned int descendFlag);

int main(int argc, char ** argv) {

    int numArray[4] = {14, 4, 16, 12};      
    int * arrayPtr = numArray;

    int x;
    for (x = 0; x < 4; x++) {
        printf("%i\n", numArray[x]);
    }

    printf("\n\n\n");           

    sortArray(arrayPtr, 4, 1);

    for (x = 0; x < 4; x++) {
        printf("%i\n\n", numArray[x]);
    }

    printf("\n\n\n");

    sortArray(arrayPtr, 4, 0);

    for (x = 0; x < 4; x++) {
        printf("%i\n\n", numArray[x]);
    }       
    return 0;
}

void sortArray(int * numbers, unsigned int n, unsigned int descendFlag) {
    int i, j;
    for (i = 0; i < n; i++) {
        for (j = i + 1; j < n; j++) {
            // Ascending
            if (descendFlag != 1 && numbers[i] > numbers[j]) {
                int temp = numbers[i];
                numbers[i + 1] = numbers[i];
                numbers[i] = temp;
            }

            if (descendFlag == 1 && numbers[i] < numbers[j]) {
                int temp = numbers[i];
                numbers[i + 1] = numbers[i];
                numbers[i] = temp;  
            }
        }
    }
}

Here's the out put for this program :

14
4
16
12



14

14

14

12




14

14

14

14

What's going wrong here ? And also am I using pointers correctly ?

I'm a new student to C and pointers are just so confusing. I don't know if I'm supposed to use & or * to access a variable passed as a pointer. What am I doing wrong ere ?

Upvotes: 0

Views: 63

Answers (1)

Haris
Haris

Reputation: 12270

you are comparing between i and j here

if (descendFlag == 1 && numbers[i] < numbers[j])

and later swapping with i and i + 1..

int temp = numbers[i];
numbers[i + 1] = numbers[i];
numbers[i] = temp;

Swap the elements of the positions that you compare

int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;

Same goes for the other comparison and swap (descendFlag != 1)


You do not need this variable

int * arrayPtr = numArray;

numArray can be directly used like this

sortArray(numArray, 4, 0);

Since the name of an array is the base address of that array.

Upvotes: 3

Related Questions