Hi happy people

I've bin trying to sort items in a list box, the problem is obviously: It doesn't work

Please, any modifications to the code below is fully and unconditionally allowed.

void __fastcall TForm1::btnSortClick(TObject *Sender)
{

        //sort ascending
       if (rdAscending->Checked){
           bool swopped = true;
           int iEnd;
           int arr = lstWords->Count;
           //ShowMessage(arr);
           iEnd = arr -1;

           while (swopped)
           {
              swopped = false;
              for (int c=0; c < iEnd; c++)
              {
                 AnsiString a = lstWords->Items->Strings[c];
                 AnsiString b = lstWords->Items->Strings[c+1];
                 if (a > b)
                 {
                    AnsiString txt = lstWords->Items->Strings[c];
                    lstWords->Items->Strings[c] = lstWords->Items->Strings[c+1];
                    lstWords->Items->Strings[c+1] = txt;
                   swopped = true;
                   iEnd--;

                }

              }
           }

'Let us do what we do best!'
       }
       //sort descending
       else if (rdDescending->Checked){
           bool swopped = true;
           int iEnd;
           int arr = lstWords->Count;
           iEnd = arr -1;

           while (swopped)
           {
              swopped = false;
              for (int c=0; c < iEnd; c++)
              {
                 AnsiString a = lstWords->Items->Strings[c];
                 AnsiString b = lstWords->Items->Strings[c+1];
                 if (a < b)
                 {
                    AnsiString txt = lstWords->Items->Strings[c];
                    lstWords->Items->Strings[c] = lstWords->Items->Strings[c+1];
                    lstWords->Items->Strings[c+1] = txt;
                   swopped = true;
                   iEnd--;

                }

              }
           }
       }
       else
        ShowMessage(
        "Select either [Ascending] or [Descending]! \nPlease Try Again!"); 
}

Can't you use qsort() for this? It'd make the code a lot shorter... and easier I guess.

And a, a bit more precise about the error? What are you getting? Segfaults or just a not-sorted listbox?

I'l try using 'qsort()'. I never new there was such a function, but now because of you I..........! ;-)

About the error, it was not an error at all. It is wrong logic that I used, and I got it al fixed!

Thanks a lot clockowl!

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.