如何?以下排序的演算法

來源:互聯網
上載者:User
如何?以下排序的演算法 Delphi / Windows SDK/API
http://www.delphi2007.net/DelphiBase/html/delphi_20061218161948124.html
有類似如下一字串:“2:牛   4:雞   1:豬   3:虎   8:猴   3:馬”如何?按生肖前面的數值從大小到的順序排列,即得到如下字串:“8:猴   4:雞   3:虎   3:馬   2:牛   1:豬”

放到TStringList裡,   調用Sort方法

sort可以針對這種字元嗎,我也有這樣想過

order   by....

這種方法不行,11   排在了2的後面。   不行。

我的思路,先分解出來,再排序,再重組  
  按你那種格式的話,就截取字串,5個一截(最後一個是4個),最多截12次  
  就可以得到  
  2:牛  
  4:雞  
  1:豬  
  ...  
  然後可以字串直接比較排序了,最後重組字串  
   
   
 

喔,不行,然後再分解一次,從後往前截3位,就可以得到前面的數字了.

用tstringlist的CustomSort就可以了,如:  
  function   mycomp(List:   TStringList;   Index1,   Index2:   Integer):   Integer;  
  var  
      p,n1,n2:integer;  
      s:string;  
  begin  
      p:=pos(':',list.Strings[index1]);  
      n1:=StrToInt(copy(list.Strings[index1],1,p-1));  
      p:=pos(':',list.Strings[index2]);  
      n2:=StrToInt(copy(list.Strings[index2],1,p-1));  
      result:=n1-n2;  
  end;  
   
  procedure   TForm1.Button1Click(Sender:   TObject);  
  var  
      t:tstringlist;  
  begin  
      t:=tstringlist.Create;  
      t.Add('1:aweqw');  
      t.Add('2:asd');  
      t.Add('4:adas');  
      t.Add('11:asdasd');  
      t.Add('15:ewr');  
      t.Add('10:sdfsdf');  
      t.Add('20:sfsd');  
      t.CustomSort(mycomp);  
      Memo1.Lines.AddStrings(t);  
  end;  
 

我的意思是先把它們排好,然後付值,按照1234…………,再進行排序就可以了,

var  
      I   :   Integer   ;  
      s                                   :   string;  
      p                                   :   pchar;  
      StringList                 :   TstringList;  
      p1                                 :   pchar;  
  begin  
      StringList   :=   Tstringlist.create();  
      s   :=   '2:牛   4:雞   1:豬   3:虎   8:猴   3:馬';  
      p   :=   @s[1];  
      p1   :=   p;  
      while   p^   <>   #0   do  
      begin  
          if   p^   =   char('   ')   then  
          begin  
              p^   :=   char(0);  
              Stringlist.add(strpas(p1));  
              inc(p);  
              p1   :=   p;  
          end;  
          inc(p);  
      end;  
      StringList.sort;  
      for   I   :=   0   to   StringList.Count   -   1   do         //   Iterate  
          begin  
              showmessage(Stringlist.Strings[i])   ;  
          end   ;         //   for  
      StringList.free;  
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.