Assert failing for modified bubble sort

My commented code is below. It a simple modified bubble sort. Problem is that the assertion to check if the array is sorted fails every time.

I have printed out the array using cout, and it is in fact sorted. However, the assertion fails. What going on?

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
void BubbleSort()
{
    srand(time(0)); // seed for random num generator

    const int n = 10;
    int arr[n]; // create array of size n
    // fill array with random numbers
    for(int i=0; i<n; i++)
    {
        arr[i] = 1 + rand()%100;
    }

    bool sorted;

    for(int i=0; i<n; i++)
    {
        sorted = true; // at every pass, array has potential of being sorted
        for(int j = 0; j < n-i-1; j++)
        { 
            if(arr[j]>arr[j+1])
            {
                swap(arr[j], arr[j+1]);
                sorted = false; // if a swap was made, array was not sorted
            }
        }
        if(sorted) // if no swaps were made, array was sorted, so break
            break;
    }

    for(int i=0; i<n-1; i++)
        assert(arr[i]<arr[i+1]);  // this assertion fails every time, even though printing the number I can see that they are sorted. 
}


Last edited on
So It seems to be working now.

However, the assertion is still failing for larger values of n, such as n=100;
assert(arr[i] <= arr[i+1]);


By the way, int arr[n]; is a VLA. Make `n' constant.
Ah, thank you. Fixed.

Now for the real issue at hand, anyone?

Are there any duplicates in your array? If so the assertion will fail.

Are there any duplicates in your array? If so the assertion will fail.


Holy....

I can't believe I didn't think of this. Thank you so much. Problem solved.
Topic archived. No new replies allowed.