简体   繁体   中英

C++ Using pointers for selection sort function

I've got a task to code some sorting function by passing pointers. Unfortunately, pointers are just one of those concepts my brain doesn't seem to comprehend.

Here's the call:

int size = 10000;
int* data = new int[size]; 
//omitted code that populates array for the sake of space
selectionSort(data, data+size); 

And here's my incorrect attempt at the function:

void selectionSort(int* first, int* last) { 
for (int* i = first; i < last-1; i++) {
    int* min = i;
    for (int* j = i+1; j < last; j++) {
        if (j < min) {
            min = j; 
        }
        int* temp = i; 
        i = min; 
        min = temp; 
    }
}

}

Basically, I'm having trouble figuring out what happens when I'm comparing one pointer with another, or adjusting a pointer. Is it adjusting/comparing the value it's pointing too or is it comparing the actual pointers themselves?

Any help is appreciated. Cheers.

Pointers are sometimes a difficult concept to grok. Perhaps it will help to think of them as a reference to a value, rather than the value itself (it's an address of the mailbox, not the contents of the mailbox).

In your code 'int* min = i;' sets min to the same address (reference) as 'i'. So later in your 'if' statement 'if (j < min)' you are comparing references, not values. You need to "dereference" your pointer to get at the values, like this: 'if (*j < *min)'.

In pointers if,

int* i; //i holds actual physical memory address & i* holds value at that address.

Now, in your selectionSort functions if condition you are comparing actual memory addresses and not values. See example here.

You should never really be put in a position that you need to create your own sort algorithm. Instead, you should always try to utilize existing collection class, eg set, which will sort for you. That being said, if your goal is to better understand pointers, then as greatwolf commented, you shouldn't be sorting pointers, but what they are pointing to! In your case integers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM