0

I am trying to sort an array recursively, by separating elements by those smaller than 9 and those that are not. What changes should I make?

(The recursive call rb(a, size); gives me a bad access error.)

void rb(int a[], int size)
{
    for(int i=0; i < size - 1; i++)
    {
        if(a[i] > 9){
           int tmp = a[i];
           a[i]=a[i+1];
           a[i+1]=tmp;
           rb(a, size);
        }
    }
}
seenukarthi
  • 8,241
  • 10
  • 47
  • 68
JCoder
  • 189
  • 1
  • 3
  • 17
  • This will result in an infinite loop if `arr[0] == arr[arr.size() - 1]` and `arr[0] < 9`. For the size question: just use a `std::vector` and you're fine. – stefan Mar 25 '15 at 17:18
  • "Raw" arrays in C++ are not classes and thus have no methods or members. If you must use raw arrays, you should pass the capacity as a parameter (C-style coding). Otherwise use a standard C++ container (`std:array`, `std::vector`, `std::list`, etc.). – crashmstr Mar 25 '15 at 17:23
  • ok, I think I fixed the infinite loop... but it still does not work – JCoder Mar 25 '15 at 17:23
  • @JCoder Nope, not slightly fixed. (You're potentially swapping two identical elements and then recurse into the sort function with identical arguments). – stefan Mar 25 '15 at 17:24
  • "arr" is a plain C array. It doesn't have a size () method, so I doubt this code will compile. On the other hand, sizeof (arr) is the size of an int*, usually 4 or 8, and not at all related to the number of elements in the array. – gnasher729 Mar 25 '15 at 17:29
  • The goal in doing a recursive sort is to break the problem up into sub-problems. It looks to me like you are passing in the exact same input to every recursive call. i.e. your initial call is is `rb(a, 5)`, and each subsequent call is `rb(a, 5)` – Taekahn Mar 25 '15 at 21:01

1 Answers1

1

The reason you couldn't use sizeof(arr) is that an array becomes a pointer when passed to a function. So, inside the function when you called 'sizeof(arr)' it was equivalent to 'sizeof(int*)' and that is why you got the error you did.

See this other SO question for an explanation (almost verbatim what I wrote).

Community
  • 1
  • 1
blh83
  • 495
  • 5
  • 17