快速排序数组

时间:2019-11-01 13:28:05

标签: sorting quicksort

我有一个数组A = | 0.535 | 0.960 | 0.750 | 0.750 | 0.151 | 0.001 | 0.981 | 0.327 | 0.111 |

我将枢轴设为0.535

我将A [1] = 0.960替换为A [8] = 0.111得到

A = | 0.535 | 0.111 | 0.750 | 0.750 | 0.151 | 0.001 | 0.981 | 0.327 | 0.960 |

然后我将A [2] = 0.750与A [7] = 0.327交换

A = | 0.535 | 0.111 | 0.327 | 0.750 | 0.151 | 0.001 | 0.981 | 0.750 | 0.960 |

现在,我对下一步做什么感到困惑(将0.75与0.75进行比较),因为值0.151小于枢轴,而0.981大于枢轴。有人可以引导我吗?

1 个答案:

答案 0 :(得分:1)

我不知道您要寻找什么。但是,如果您想知道快速排序的工作原理,那么请遍历数组。应该提到的是,我们将把最左边的元素作为数据透视。

    function qsort(x, lo, hi) {
      var i, p;
      if (lo >= hi) {
          return;
      }
      p = lo;
      for (i = lo + 1; i <= hi; i++) {
        if (x[i] < x[lo]) {
            swap(x, ++p, i);

         }
      }
    swap(x, lo, p);
    qsort(x, lo, p - 1);
    qsort(x, p + 1, hi);
    }

正如您所说,第一步获得0.535作为枢轴,它将经过第二个元素(来自枢轴)遍历您的元素,如果它小于选定的枢轴,则它将与第二个元素一起更改该元素的位置,如果它发现第二个元素较小,它将随着第三个元素的位置而改变,依此类推。最后,它将使用大于其的position = total元素更改枢轴的位置。因此,选择0.535后,数组将如下所示:

[0.111,0.151,0.001,0.327,0.535,0.75,0.981,0.75,0.96]。

然后该枢轴将为0.111,然后数组将如下所示:

[0.001,0.111,0.151,0.327,0.535,0.75,0.981,0.75,0.96]。

再次枢轴= 0.151和数组:

[0.001,0.111,0.151,0.327,0.535,0.75,0.981,0.75,0.96]

再次枢轴= 0.75和数组:

[0.001,0.111,0.151,0.327,0.535,0.75,0.981,0.75,0.96]

再次枢轴= 0.981和数组:

[0.001,0.111,0.151,0.327,0.535,0.75,0.96,0.75,0.981]

再次枢轴= 0.96和数组:

[0.001,0.111,0.151,0.327,0.535,0.75,0.75,0.96,0.981]