Hello,

I have an array and need to sort it so that the highest numbers show first etc..

I have written this:

for(int i=0; (i < 26); i++)
    {
        while(counter[i] < counter[i + 1])
        {
            int temp = counter[i];
    
            counter[i + 1] = temp;
            counter[i] = counter[i + 1];
            
            cout << counter[i];
            cout << counter[i + 1];
        }
    
        cout << " " << alphabetUpper[i] << " " << counter[i] << endl;
        
    }

But it doesn't seem to be working? Any ideas? Thanks

Recommended Answers

All 3 Replies

A couple ideas:
1) Your swapping code in lines 6-9 is broken. Watch the order of those lines.
2) If your swapping was correct, your inner loop would execute either once or not at all, so it should just be an if() statement
3) Once you've found two values to swap, you can't just blindly go on as if nothing happened -- instead of blindly hacking at it, do this with a real physical deck of playing cards (one suit is enough): shuffle them up, lay them out in a row, and start swapping neighboring cards as needed. Start at one end of the row and see what you need to do each time you find a pair to swap, until your row is sorted into order. Now write that logical process into code.

Oh, and the sort involving swapping successive neighbors is "bubble sort", not "insertion sort" ... if you need to implement insertion sort, then the procedure is different: take an item out of a scrambled list, and add it into the correct place in a new list, moving items out of the way as needed. You can do this in-place using a single array by keeping track of how many items K you've inserted. The first K items should be in sorted order, and the remaining N-K items are the scrambled items remaining to sort.

Either way, hand-sorting N real-world objects (where N is big enough to eliminate trivial answers, and small enough that you can finish in a reasonable amount of time) will really drive home the logic involved.

Thanks for your help I have managed to solve this now (thankfully) but thank you :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.