Quick Sort

Hi,

I'm currently trying to convert a sorting algorithm from using two ints and an array to only using two pointers.

below is currently what I am using but it is returning errors, is anyone able to offer any assistance?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int* partition (int* first, int* last) {
    int pivot = *(last -1);
    int* i = first;
    int* j = last;
    
    for (;;){
        while (*i < pivot && *i < *last) ++i;
        while(*j >= pivot && *j > *first) --j;
        if (*i >= *j) break;
        swap (*i, *j);
    }
    swap (*last, *i);
    return i;
}

void quickSort(int* first, int* last) {
    if (first - last <= 1) return;
    int* pivot = partition(first, last);
    quickSort(first, pivot);
    quickSort(pivot +1, last);
}
How does your function know the length of the array? You seem to be accessing memory that does not belong to you which I why I believe the OS is complaining
Smac89: The code follows the convention of first == the first element in the sequence, last == one past the last element in the sequence, so length == last - first.

arvust: Your check on line 17 is backwards. It should be last - first <= 1.
As a matter of convention, use the names begin and end in the future. 'Last' is a misnomer, since the pointer doesn't point to the last element in the sequence.
Topic archived. No new replies allowed.