各位朋友,假如有一组数字,1、11、15、17、21、23、29,然后用户随意给出一个整数,如:19,如果采用循环的方式来进行排序,虽然可以排列出以下结果:1、11、15、17、19、21、23、29,但如果该组数字多的话,速度可能会比较慢。但小弟想采用折半的思路来进行排序,即先将19与该组数字的中间数进行比较,如果19大于该组数字的中间数,那么就直接与剩下的数字的中间数进行比较,依次类推,但虽然有这样的思路,但具体的实现方法却不知道如何做,能否帮忙写一个简单的例子,谢谢!

解决方案 »

  1.   

    这是自己用循环作的,测试通过,可以成功排序,但希望有高手能帮忙改进一下,用折半的方法来解决该问题,谢谢!!!var
      arr_str: array of integer;
      arr_new: array of integer;
      i, j, k, tmp: integer;
    begin
      tmp := StrToInt(Trim(edit1.Text));
      SetLength(arr_str, 4);
      SetLength(arr_new, 5);
      j := 0;
      arr_str[0] := 1;
      arr_str[1] := 5;
      arr_str[2] := 8;
      arr_str[3] := 11;
      for i := low(arr_str) to high(arr_str) do
        begin
          if tmp > arr_str[i] then
            begin
              arr_new[i] := arr_str[i]
            end
          else
            begin
              arr_new[i] := tmp;
              j := 1;
              Break;
            end;
        end;
      k := i + 1;
      if j = 1 then
        begin
          for j := k to high(arr_str) + 1 do
            begin
              arr_new[j] := arr_str[i];
              i := i + 1;
            end;
        end
      else
        begin
          arr_new[high(arr_str) + 1] := tmp;
        end;
      for i := low(arr_new) to high(arr_new) do
        ShowMessage(IntToStr(arr_new[i]));
    end;
      

  2.   

    自己看一下那本严渭敏的蓝皮C版<数据结构>或绿皮的pasal版,里面就有这算法,好久没看了,忘了具体是怎么样了
      

  3.   

    这是我编的一个折半查找的函数,如果你要折半排序的话,就要中间的和后面的两个值进行比较了,然后找到自己的合适位置后再插入
    function Reducebyhalffind(d:integer;arr:array of integer):integer;
    var
    firstindex,lastindex,midindex,i:integer;
    begin
    result:=0;
    firstindex:=low(arr);
    lastindex:=high(arr);
    if (lastindex-firstindex)>2 then
      repeat
      midindex:=(firstindex+lastindex)div 2;
      if d>arr[midindex] then
         firstindex:=midindex+1
         else if d<arr[midindex] then
            lastindex:=midindex-1
            else if d=arr[midindex] then
               begin
               result:=midindex;
               break;
               exit;
               end;
      until (lastindex-firstindex)<3;
    for i:=firstindex to lastindex do
       if arr[i]=d then
          begin
          result:=i;
          break;
          end;
    end;