0

The sortArray method is to sort numbers in an array.

static void sortArray(int numbers[])
{
    //bubble sort
    for (int i = 0; i < sizeof(numbers) / sizeof(int); i++) {
        for (int j = 0; j < sizeof(numbers) / sizeof(int) - 1; j++) {
            if( numbers[j] > numbers[j + 1]){
                int temp = numbers[j];
                numbers[j] = numbers[j + 1];
                numbers[j + 1] = temp;
            }
        }
    }

    for (int i = 0; i < sizeof(numbers) / sizeof(int); i++) {
        int j = numbers[i];
        cout << j << (" ");
    }
}

The main method is to print out unordered numbers and the result.

int main()
{
    int numbers[] = {4,2,1,3};
    cout << ("Before sorting:") << endl;
    for (int i = 0; i < sizeof(numbers)/sizeof(int); i++) {
        int j = numbers[i];
        cout << j << (" ");
    }
    cout << ("\nAfter sorting:\n");
    sortArray(numbers);
    cout << ("") << endl;
}

Output:

Before sorting:
4 2 1 3
After sorting:
2 4

Note: I have tried to run this program in Java and it worked just fine. But, in C++ it only sorts the first two numbers.

  • Note: C++ and Java are different languages, most likely your Java code was not doing the same, because `sizeof(numbers)` is not doing what you think it does – 463035818_is_not_an_ai Oct 18 '21 at 10:17
  • 1
    When you declare an argument like `int numbers[]` it's really the same as `int* numbers`. And the size of a pointer is the size of the pointer itself, not what it points to. You should use `std::vector` (or `std::array`, if the size is a compile-time constant). – Some programmer dude Oct 18 '21 at 10:18
  • most problems with c-arrays go away when you use `std::vector` instead – 463035818_is_not_an_ai Oct 18 '21 at 10:18

0 Answers0