LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   ascending order (https://www.linuxquestions.org/questions/programming-9/ascending-order-345807/)

huno 07-22-2005 04:21 PM

ascending order
 
how can i check if the array element in ascending order using recursive ?

itsme86 07-22-2005 05:34 PM

Shall we just a pick a programming language at random and hope that's the one you're asking about?

coldAndUgly 07-22-2005 06:23 PM

Quote:

Shall we just a pick a programming language at random and hope that's the one you're asking about?
Why not? :p
Here's an implementation in C++.
Code:

#include <iostream>

using std::cout;
using std::endl;

bool isInAscendingOrder(const int*, const unsigned int);
static bool checkArray(const int*, const int*, const int* const);

int main()
{
    const unsigned int s = 10;
    int a[s] = { 0, 1, 2, 4, 3, 5, 6, 7, 8, 9 };

    if (isInAscendingOrder(a, s))
        cout << "Array \"a\" is in ascending order." << endl;
    else
        cout << "Array \"a\" is not in ascending order." << endl;

    return 0;
}

bool isInAscendingOrder(const int* arr, const unsigned int size)
{
    if (size == 0)
        return false;

    const int* e1 = arr;
    const int* e2 = arr + 1;
    const int* end = arr + size;        // First address beyond the end of the array is always valid.

    return checkArray(e1, e2, end);
}

static bool checkArray(const int* a, const int* b, const int* const c)
{
    if (b == c)                        // We've checked every element of the array and it's in order.
        return true;
    else if (*b < *a)                  // We've found two elements that aren't in order.
        return false;

    return checkArray(++a, ++b, c);    // Check the next element.
}


itsme86 07-22-2005 06:42 PM

And here's a C one that even tells you were the order breaks and uses one less function than that C++ version ;)
Code:

#include <stdio.h>

int chk_ascending(int *array, int index, int size)
{
  if(index >= size - 1)
    return 0;
  if(array[index] > array[index + 1])
    return index + 1;

  return chk_ascending(array, index + 1, size);
}

int main(void)
{
  int a[] = { 0, 1, 2, 4, 3, 5, 6, 7, 8, 9 };
  int num_a = 10;
  int rv;

  if(!(rv = chk_ascending(a, 0, num_a)))
    puts("Array \"a\" is in ascending order.");
  else
    printf("Array \"a\" breaks ascending order at index %d.\n", rv);

  return 0;
}


coldAndUgly 07-22-2005 07:03 PM

Well done, I like your version better.
My coding skills are a little rusty :D


All times are GMT -5. The time now is 12:32 PM.