Exchange sorting algorithm in c using pointers

I am trying to write an exchange sort in c using pointers, not indices;

I don't understand why this code doesn't work:

void sort(int a[], int n) {
  int *i, *j, *temp;
  int * const end = a + n;

  for(i = a; i < end - 1; i++)
    for(j = i + 1; j < end; j++)
      if(*i > *j) {
        temp = i;
        i = j;
        j = temp;
      }
}

      

If I write this code mostly swap works fine:

int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int *i = a;
int *j;
int *temp;

i = a;
j = a + 1;
printf("pre-swap - i: %i | j: %i\n", *i, *j);

temp = i;
i = j;
j = temp;
printf("post-swap: i: %i | j: %i\n", *i, *j);

      

It changes two values โ€‹โ€‹successfully.

But when using this code, it does nothing for the array:

sort(a, 10);

      

Why isn't my sorting algorithm working?

+3


source to share


1 answer


Here's the correct solution:

void sort(int a[], int n) {
int *i, *j, temp;
int * const end = a + n;

    for(i = a; i < end-1; i++) {
        for(j = i + 1; j < end; j++) {
            if(*i > *j) {
                temp = *i;
                *i = *j;
                *j = temp;
            }
        }
    }
}

      



What others have commented above is absolutely correct. You must use dereference. Learn more about pointers, and use debugging. If you don't know then start by printing all values.

+3


source







All Articles