Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting with pointers instead of indexes

Tags:

arrays

c

sorting

I'm trying to sort an pointer array using pointers instead of indexes but I'm not entirely sure on how to do this. I've been googling but haven't found anything releveant.

I've got the sorting to work just fine using indexes but I want to do it by using pointers too. Currently the function looks like this:

void sort(int *pointer, int size){
    int i, j, temp;
    for(i = 0; i < size; i++){
        for(j = i + 1; j < size; j++){
            if(pointer[j] < pointer[i]){
                temp = pointer[j];
                pointer[j] = pointer[i];
                pointer[i] = temp;
            }
        }
    }
}

As you can see the array indexes is being used, how would I do this using only the pointer?

like image 276
Kraffs Avatar asked Mar 18 '26 13:03

Kraffs


1 Answers

It would be quite annoying. You need to use the fact that in C, a[i] == *(a + i), and thus this:

if(pointer[j] < pointer[j])

would become

if(*(pointer + j) < *(pointer + j))

and so on. There's really no difference, except that the indexing code is far easier to read. :)

like image 72
unwind Avatar answered Mar 21 '26 03:03

unwind