Kguy
Kguy

Reputation: 3

Sorting an array fail

I'm trying to sort an array made of random numbers from 1 to 10 in an ascending order. I've come up with this function:

void Sort(int a[10], int n)
{
    int j = 0;
    for (int i = 0; i < n-1; i++)
    {
        j = i+1;
        if (a[i] > a[j])
        {
            int aux = a[i];
            a[i] = a[j];
            a[j] = aux;
        }
    }
}

But when I try to output the array, the function doesn't seem to have worked:

Sort(array, 10);

    cout<<endl;

    for (int i = 0; i < 10; i++)
    {
        cout<<array[i]<<" ";
    }

Upvotes: 0

Views: 184

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361762

The algorithm in your Sort function is wrong. It doesn't sort at all.

Anyway, don't reinvent the wheel, better use std::sort as:

#include <algorithm>

std::sort(array, array+10);

As for your Sort function, which you want to implement using bubble-sort algorithm, possibly for learning purpose. the correct implementation is this:

void Sort(int *a, int n)
{
    for (int i = 0; i < n ; i++)
    {
       for (int j =  i + 1; j < n ; j++)
       {
           if (a[i] > a[j])
           {
              int aux = a[i];
              a[i] = a[j];
              a[j] = aux;
           }
       }
    }
}

Upvotes: 2

Jeff Foster
Jeff Foster

Reputation: 44746

You are only making n swaps. You need an outer loop on sort (assuming it's bubble sort) so that you continue doing that until you stop doing swaps.

bool Sort(int a[10], int n)
{
    bool swapped = false;
    int j = 0;
    for (int i = 0; i < n-1; i++)
    {
        j = i+1;
        if (a[i] > a[j])
        {
            int aux = a[i];
            a[i] = a[j];
            a[j] = aux;
            swapped = true;
        }
    }
    return swapped;
}

int main(int argc, char** argv) {
    int a[10] = {5,4,3,1,2,6,7,8,9,10};
    while (Sort(a,10));

    for (int i=0;i<10;++i) {
        std::cout << a[i] << std::endl;
    }
}

Upvotes: 1

Andrew Marsh
Andrew Marsh

Reputation: 2082

That only does one pass over the data, here is an example showing you what happens

8 7 9 2 3 4 5

After going through your function the result would be

7 8 2 3 4 5 9

Upvotes: 0

Related Questions