Eid Eid - 1 year ago 123
C Question

How to sort an array by passing to a function as pointer using c?

I want to sort an array using a function. The array should be passed to the function swap() that swaps the current numbers in the array. The code in the picture is taken from a book, which I am going to implement to show that it has faster execution time as compared to other sorting methods.
function in c-code that sorts an array

I have done it in the following way, but fail to sort the array:

void swap(int* c, int* d){
int temp, ai, aj;
ai = *c;
aj = *d;
if (ai > aj) /* For decreasing order use < */
*c = aj;
*d = ai;


int main()
int array[] = {1,3,5,7,9,2,0,3};

for (int c = 0 ; c <8-1; c++)
for (int d = c+1 ; d < 8; d++)
swap(&array[c], &array[d]);

return 0;

Answer Source

1) Sorting only affected local contents.

    temp = aj;
    aj = ai;
    ai = temp;

Code needs to update values referenced by original pointers.

void swap(int array1[], int array2[]){
  int ai = *array1;
  int aj = *array2;
  if (ai > aj) {
    *array1 = aj;
    *array2 = ai;

2) Code needs to call the swap() correctly. It expect pointers, not int. This implies compiler warnings are not fully enabled. Be sure to do so - saves you time.

// swap(array[c], array[d]);
swap(&array[c], &array[d]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download