首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有人能解释一下这种快速排序方法吗?

有人能解释一下这种快速排序方法吗?
EN

Stack Overflow用户
提问于 2013-11-03 19:38:20
回答 1查看 127关注 0票数 0

你们能解释一下这种快速排序方法吗?我正在尝试将这段代码实现到我的程序中,但是作者没有解释它做了什么,或者它是如何实现的。也请注意,我在高中,所以请尽量保持它可以理解。

我所知道的是它加快了二维数组的速度。我还知道它使用递归来执行它的快速排序。不幸的是,就是这样。任何帮助都将不胜感激。

代码语言:javascript
复制
public double[][] quicksort(double[][] array, int key, int down, int top) {
    double[][] a = new double[array.length][2];
    System.arraycopy(array,   0, a, 0, a.length);

    int i = down;
    int j = top;
    double x = a[(down + top) / 2][key];

    do {
      while (a[i][key] < x) {
        i++;
      }
      while (a[j][key] > x) {
        j--;
      }
      if (i <= j) {
        double[] temp = new double[a[i].length];

        for (int y = 0; y < a[i].length; y++) {
          temp[y] = a[i][y];
          a[i][y] = a[j][y];
          a[j][y] = temp[y];
        }
        i++;
        j--;
      }
    } while (i <= j);

    if (down < j) {
      a = quicksort(a, key, down, j);
    }

    if (i < top) {
      a = quicksort(a, key, i, top);
    }

    return a;
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-03 19:44:39

有几件事要知道:

  • array是键值对的数组,它是按键排序的.
  • 此快速排序返回原始数组的副本,而不是更改现有的数组。

见评论:

代码语言:javascript
复制
public double[][] quicksort(double[][] array, int key, int down, int top) {
    //create copy of array (the author wanted to return a new one)
    double[][] a = new double[array.length][2];
    System.arraycopy(array,   0, a, 0, a.length);

    int i = down; //lower limit
    int j = top;  //upper limit
    double x = a[(down + top) / 2][key]; //the pivot

    do {
      while (a[i][key] < x) { //skip over smaller elements in beginning
        i++;
      }
      while (a[j][key] > x) { //skip over larger elements in end
        j--;
      }

      //now do some partitioning
      if (i <= j) {
        //create temporary array, for swapping elements
        double[] temp = new double[a[i].length];

        for (int y = 0; y < a[i].length; y++) {
          temp[y] = a[i][y];
          a[i][y] = a[j][y];
          a[j][y] = temp[y];
        }
        i++;
        j--;
      }
    } while (i <= j);

    //if there is a non-empty lower partition, sort that
    if (down < j) {
      a = quicksort(a, key, down, j);
    }

    //if there is a non-empty upper partition, sort that
    if (i < top) {
      a = quicksort(a, key, i, top);
    }

    //return the result
    return a;
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19757164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档