Vellop
Vellop

Reputation: 37

Function that checks if an array is sorted

So I'm just a beignner programmer when it comes to C++, and I have to write a function that checks if an int array is sorted using pointers (no index notations allowed), and here's what I have so far:

bool isSorted(const int *ar, int size) {
    bool sorted = true;
    const int *ptr1, *ptr2, *ptr3;
    ptr1 = ar;
    ptr2 = ar+1;
    ptr3 = ar+size;

    for (ptr1; ptr1 < ptr3; ptr1++) {
        for (ptr2; ptr2 < ptr3; ptr2++) {
            if (*ptr1 > *ptr2) {
                sorted = false;
            }
        }
    }
    return sorted;
}

However, I can't seem to get it to work as it always returns true regardless of whether the array is sorted or not. Any help is appreciated, thanks.

Upvotes: 2

Views: 3780

Answers (2)

WIND.Knight
WIND.Knight

Reputation: 346

You should keep ptr2 always be ptr+1,so you need to initialize ptr2 in second for() . And I think only one loop is better.

for(; ptr2 < ptr3; ++ptr1, ++ptr2) {
    if (*ptr1 > *ptr2) {
        sorted = false;
    }
}

return sorted;

Upvotes: 0

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

"The more you overthink the plumbing, the easier it is to stop up the drain" -- Scotty, Star Trek III.

You are making this much more complicated than it has to be.

Ask yourself a basic question: what is a sorted array?

Answer: an array in which each successive element is not less than its preceding element.

Therefore: to check if the array is sorted, just look for an element that's less than its previous element. If you found one, the array is not sorted. If you couldn't find one, the array must be sorted.

bool isSorted(const int *ar, int size) {

    if (size == 0)
        return true;   // Edge case

    int previous_value= *ar;

    while (size)
    {
       if (*ar < previous_value)
             return false;
       previous_value= *ar;

       ++ar;
       --size;
     }
     return true;
}

No index notations, just a single pointer. No need to do any kind of a nested search, etc... If you want to use only pointers, you could do this:

bool isSorted(const int *ar, int size) {

    const int *previous_value=ar;

    while (size)
    {
       if (*ar < *previous_value)
             return false;
       previous_value= ar;

       ++ar;
       --size;
     }
     return true;
}

Actually, I like this version even better.

Upvotes: 3

Related Questions