Huang Elizabeth
Huang Elizabeth

Reputation: 23

c++: check array's order

I have tried to write a bool function, accepted an array and a bool dec. If dec is true than the function will check it's descending and return true if it's descending. If dec is false than the function will return true if it's ascending.

If I test the array with this function, it should return false, but it gives true, and I don't know why. Can anyone help? thanks.

#include <iostream>
#include <cstring>
#include <cmath>

#include <iomanip>

using namespace std;

bool isSorted(int array[], int size, bool dec) //false decending
{
    bool check = true;

    if (dec == false)
        for (int i = 0; i<size; i++)
            if (array[i]>array[i + 1])
            {
                check = false;
                cout << "false";
            }

    else
        for (int i = 0; i<size; i++)
            if (array[i]<array[i + 1])
                check = false;

    return check;
}


int main() {
    int n;
    bool asc=true;
    bool result;
    int arr[] = { 1, 2, 4, 3, 0 };
    n = 5;

    result = isSorted(arr, n, asc);
    cout << result;
    system("pause");
}

Upvotes: 0

Views: 1148

Answers (3)

CiaPan
CiaPan

Reputation: 9570

The value you pass to the function is named asc while the parameter for it is dec. Check again if you actually do what you want.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726589

You have an off-by-one error: when you reach the last element and i is one less than size, arrat[i+1] is referencing an element past the end of the array.

Since changing check to false is a "one way street", you can simplify your function by returning false as soon as you detect a wrong order; return true when you reach the end of the function.

You can also move the ascending/descending check inside the loop to make the code even more uniform:

for (int i = 0; i < size-1 ; i++) {
    if (des && (array[i]<array[i + 1])
    || !des && (array[i]>array[i + 1])) {
        return false;
    }
}
return true;

Upvotes: 3

Olayinka
Olayinka

Reputation: 2845

You're accessing beyond the boundary of the array, change the loop to

  for (int i = 0; i < size-1; i++)

So when you get to size - 2 you compare the last two elements and you're done.

Also you can return immediately after finding an exception instead of completing the iteration.

Upvotes: 1

Related Questions