Link to home
Start Free TrialLog in
Avatar of searchsanjaysharma
searchsanjaysharma

asked on

Why this code gives ascii codes using pointers.

I am writing a program of sorting a string with bubble sort using pointers. Works fine if len<9. But if len>9, it gives ascii values.

Why it is so.PTRSORT.CPP
Avatar of kaufmed
kaufmed
Flag of United States of America image

Are you certain that what you are doing is a bubble sort? All of the implementations that I have seen use simple swapping between two array elements rather than comparing a copy of the input to the original.

e.g.

int sort(char* const str, const int strLength, char* result)
{
    int swapOccurred = true;

    if (result == NULL)
    {
        return false;
    }

    strncpy(result, str, strLength + 1);

    while (swapOccurred)
    {
        swapOccurred = false;

        for (int i = 0; i < strLength - 1; i++)
        {
            if (*(result + i + 1) < *(result + i))
            {
                char c = *(result + i + 1);

                // SWAP
                *(result + i + 1) = *(result + i);
                *(result + i) = c;
                swapOccurred = true;
            }
        }
    }

    return true;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of sarabande
sarabande
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of searchsanjaysharma
searchsanjaysharma

ASKER

tx