Search code examples
c++bubble-sort

Bubble Sorting Function in C++


Array of Reference is not Allowed. I know in C++ it is illegal. But, is there another way to do this? I'm sure there is, but I cannot figure it out.

#include <iostream>
using namespace std;

#define UBound(n)   sizeof(n) / sizeof(n[0]);

void SortArray(int & Arr[]) {
    int ArrayLength;
    ArrayLength = UBound(Arr);
    int Min, Temp;
    for (int i = 0; i = ArrayLength; i++) {
        for (int j = 0; j = ArrayLength; j++) {
            if (Arr[i+1] < Arr[i]){
                Temp = Arr[i+1];
                Arr[i+1] = Arr[i];
                Arr[i] = Temp;
                }
        }
    }
} 
void main() {
    int numArray[9] = { 9, 7, 6, 8, 4, 5, 3, 2, 1 };
    SortArray(numArray);
} 

Final Function:

 template < size_t I >
    void SortArray(int(&Arr)[I]) {
        int Min, Temp;
         for (int i = 0; i < I - 1; i++) {
            for (int j = 0; j < I - 1; j++) {
                if (Arr[j+1] < Arr[j]){
                    Temp = Arr[j+1];
                    Arr[j+1] = Arr[j];
                    Arr[j] = Temp;
                }
            }
        } 
    } 

Thanks everyone for your answers.


Solution

  • There is, but it's not necessarily one you should use:

    template < size_t I >
    void SortArray(int (&Arr)[I]) {}
    

    Now you'll be able to use I and sizeof Arr will report as if it was on the function's local variable stack.

    Reason you probably don't want to do this is that every size array will create a new copy of the function. Could result in massive bloat.

    But I used this technique to make a constexpr string type.