字符串排序等算法

来源:互联网 发布:在淘宝上卖什么好呢 编辑:程序博客网 时间:2024/05/22 00:06

15,1,5,10,13,14,50,4,55,8,67,68,69,3,12,57,70,74 字符串,排序后再把连续数字用-连接在一起,结果为:1,3-5,8,10,12-15,50,55,57,67-70,74

  1. function   NumberSort(List:   TStringList;   Index1,   Index2:   Integer):   Integer;
  2. var
  3.     Value1,Value2:Integer;
  4. begin
  5.     Value1:=StrToInt(List[Index1]);
  6.     Value2:=StrToInt(List[Index2]);
  7.     if   Value1<Value2   then
  8.         Result:=-1
  9.     else   if   Value1>Value2   then
  10.         Result:=1
  11.     else
  12.         Result:=0;
  13. end;
  14. procedure TForm1.btn3Click(Sender: TObject);
  15. var
  16.     strTemp:string;
  17.     strs:TStringList;
  18.     i,j:integer;
  19. begin
  20.     strTemp:='15,1,5,10,13,14,50,4,55,8,67,68,69,3,12,57,70,74';
  21.     strs:=TStringList.Create;
  22.     strs.Delimiter:=',';
  23.     strs.DelimitedText:=strTemp;
  24.     strs.CustomSort(NumberSort);
  25.     i:=1;
  26.     strTemp:=strs[0];
  27.     while true do
  28.     begin
  29.         if i>=strs.Count then
  30.             break;
  31.         if StrToInt(strs[i])-StrToInt(strs[i-1])=1 then
  32.         begin
  33.             for j:=i to strs.Count-2 do
  34.                 if StrToInt(strs[j+1])-StrToInt(strs[j])=1 then
  35.                     continue
  36.                 else
  37.                     break;
  38.             i:=j;
  39.             strTemp:=strTemp+'-'+strs[i];
  40.         end else
  41.             strTemp:=strTemp+','+strs[i];
  42.         inc(i);
  43.     end;
  44.     Memo1.Lines.Text:=strTemp;
  45.     strs.Free;
  46. end;
原创粉丝点击