【问题标题】:Arranging ArrayList of Strings with quicksort not working correctly使用快速排序排列字符串的 ArrayList 无法正常工作
【发布时间】:2014-02-07 17:22:29
【问题描述】:

我有一个由字符串组成的ArrayList,全部小写,没有唯一字符。我想按字母顺序排列这个ArrayList,我尝试使用“快速排序”,但是我注意到一个问题,即我的lo 在算法将获得的第一个枢轴放置在正确位置后无法正确计算。

例如,如果我的数组由a, d, e, c, a 组成,在我的快速排序将枢轴a 放在正确位置并开始对数组的另一侧进行排序后,它从e 开始而不是d 导致结果成为a, d, a, c, e

代码:

    private ArrayList<String> sort(ArrayList<String> ar, int lo, int hi){
        if (lo < hi){
            int splitPoint = partition(ar, lo, hi);
            sort(ar, lo, splitPoint);
            sort(ar, splitPoint +1, hi);
        }
        return ar;
    }

    private int partition(ArrayList<String> ar, int lo, int hi){
        String pivot = ar.get(lo);
        lo--;
        hi++;
        while (true){
            lo++;
            while (lo<hi && ar.get(lo).compareTo(pivot) < 0){
                lo++;
            }
            hi--;
            while (hi>lo && ar.get(hi).compareTo(pivot) > 0){
                hi--;
            }
            if (lo<hi){
                swap(ar, lo, hi);
            }else {
                return hi;
            }
        }
    }

方法被称为算法:

    public Document(String fName){
         ArrayList xa = loadFile(fName);
        sort(xa, 0, xa.size() - 1);    
    }

我尝试调试了很多次,但我一直迷失在编译器开始向上堆栈树的部分。为什么我的lo 比需要的值高一个?这是什么原因造成的?

交换方法:

   private ArrayList<String> swap(ArrayList<String> ar, int a, int b){
        String temp = ar.get(a);
        ar.set(a, ar.get(b));
        ar.set(b, temp);
        return ar;
    }

注意:我从位置 0 的枢轴开始

【问题讨论】:

  • 我可以建议你在你的应用程序中加入一些日志来看看发生了什么。
  • 在 while 循环之后,您似乎忘记将枢轴与 hi 交换。
  • 假设这是一个学习练习,用笔和纸跟随你的代码是很有启发性的。

标签: java algorithm arraylist quicksort


【解决方案1】:

您必须考虑分区方法中的相等大小写。 您只需像这样更改第二个:

while (hi>lo && ar.get(hi).compareTo(pivot) >= 0){

【讨论】:

  • 这是有道理的。我忘了考虑到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 2016-07-06
  • 1970-01-01
相关资源
最近更新 更多