How can I sort a vector in a descending order in C?

I have to sort the vector in a descending order, and it doesn't work, this is the algorithm, that I tried to use.

do{
    ok=1;
    for(int i=0;i<n;i++)
        if(v[i]<v[i+1])    //is the problem here?
    {
            x=v[i];v[i]=v[i+1];v[i+1]=x;
            ok=0;
    }
}while(ok!=0);

Upvotes: 0

Views: 157

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

The expression in the if statement

if(v[i]<v[i+1])

can access memory outside the array when i is equal to n - 1.

You can rewrite the for loop for example the following way

for(int i=1;i<n;i++)
    if(v[i-1]<v[i])    //is the problem here?
{
        x=v[i-1];v[i-1]=v[i];v[i]=x;
        ok=0;
}

A more efficient implementation of the bubble-sort algorithm using your approach can look for example the following way

    int m = n;
    do {
        int last = 0;
        for (int i = 1; i < m; i++)
            if (v[i-1] < v[i])
            {
                int x = v[i-1]; v[i-1] = v[i]; v[i] = x;
                last = i;
            }
        m = last;
    } while ( !( m < 2 ) );

Upvotes: 2

Related Questions