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
C++

Avatar of undefined
Last Comment
searchsanjaysharma

8/22/2022 - Mon
kaufmed

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
sarabande

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
searchsanjaysharma

ASKER
tx
Your help has saved me hundreds of hours of internet surfing.
fblack61