algorithm - 二进制插入排序算法重复输出

标签 algorithm pascal

  for i:= 1 to 5 do
      begin
        temp := data[i];
        bawah := 1;
        atas := i;
        k:=i;   
        while (bawah < atas) do
          begin
          tengah := (bawah + atas) div 2;

          if (temp <= data[tengah]) then
              atas := tengah
          else
              bawah := tengah + 1;
          end;

          while (k > atas) do
            begin
              data[k] := data[k - 1];
              data[atas] := temp;
              k-=1;
            end;
      end;

问题是,有序的数组并不完全 结果是这样的:

enter image description here

最佳答案

您太早执行以下作业:

data[atas] := temp;

在循环的下一次迭代中,k-1 的值将变为 atas,因此错误的值将被复制到 data[k ],导致 data[atas] 中的原始值重复和丢失。

因此将该行移出循环:仅当移位操作完成时才需要执行:

      while (k > atas) do
        begin
          data[k] := data[k - 1];
          k-=1;
        end;
      data[atas] := temp;

关于algorithm - 二进制插入排序算法重复输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41777073/

相关文章:

python - 计算元素仅为相邻整数的矩阵的排列数

performance - 当我选择中位数或模式等枢轴时,快速排序的速度并不快

arrays - 什么是一致数组?

delphi - 对第二个数组中的字符进行排序,同时将其替换为旧数组中的 '*'

python - 如何将具有定义的共享子字符串的列表中的字符串移动到新列表?

algorithm - 绘制具有较大值但值变化较小的图形

python - 堆排序Python实现

algorithm - Pascal 中的 Pos() 函数使用什么算法?

inno-setup - Inno Setup - FileCopy 在路径名中使用通配符

将 Pascal 的 "shr"转换为 C 的 ">>"