Arrays

Help need it...

Using a Bubble Sort Algorithm, sort the contents of the following array in ascending order.

int numbers[4] = {23, 46, 12, 35};

4. Add appropriate C++ Comments to explain the logic behind your chosen method for solving the problem.

5. Use the appropriate data types, variables, and constant variables to solve the program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>

int main()
{
        int numbers[4] = {23, 46, 12, 35};

        // Sorts through numbers until i is 4
        // 4 being the quantity of numbers in the array

        for (int i{0}; i < 5; i++)
        {
                // Stops comparing numbers at the end of array

                for (int n{0}; n < 3; n++)
                {
                        // Checks if the element is greater than the next element

                        if (numbers[n] > numbers[n + 1])
                        {
                                // Switches the element and the one after that
                                
                                // Stores value of first element in temporary variable
                                int Temp = numbers[n];

                                // Replace first element with second element
                                numbers[n] = numbers[n + 1];

                                // Replace first element with the value of second element
                                // stored in Temp
                                numbers[n + 1] = Temp;
                        }
                }
        }

        return 0;
}
Last edited on
Thank you for the reply, now when i run the program it really doesn't show the array in ascending order, it just exist me out... and also my teacher left a comment on it saying " Remember to display after sort"
Topic archived. No new replies allowed.