Very simple question

I have an aray sum[256] which contains these numbers:

48
58
62
46
42

and i don't know how to sort them so it would go from the largest to the smallest number
Google for c++ sort algorithm

The easiest to understand is the bubble sort which is ok for a small array but becomes slow for larger arrays.

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
37
38
39
40
41
42
43
44
#include <iostream>

using namespace std;

int main()
{
    int myArray[10] = {0,1,2,3,4,5,6,7,8,9};
    int swapFlag = 1;  // flag=0 no swaps done set to 1 to start
    int temp;          // holds a number

    // show the unsorted array
    for (int i=0; i<10; i++)
    {
        cout << myArray[i] << " ";
    }
    cout << endl;

    // do the sorting ...
    swapFlag = 1;
    while (swapFlag == 1)   // while swaps have been done
    {
        swapFlag = 0;  // set to no swaps
        for (int i=0;i<9;i++)  // not 9 not 10 because we look for i+1
        {
            if (myArray[i] < myArray[i+1])  // swap if current value is less than next value
            {
                temp = myArray[i];
                myArray[i] = myArray[i+1];
                myArray[i+1] = temp;
                swapFlag = 1;   // flag a swap took place
            }

        }
    }

    // sorting done print result
    for (int i=0; i<10; i++)
    {
        cout << myArray[i] << " ";
    }
    cout << endl;

    return 0;
}

Last edited on
Can you explain the use of
swapFlag
?
It is used to say if any swaps took place in the for/next loop.
If no swaps took place in the for/next loop then the array is sorted.
Topic archived. No new replies allowed.