QuickSort不够快

时间:2014-04-17 08:57:42

标签: java sorting linked-list quicksort

注意:这与作业问题有关

我正在尝试对一个可变大小的LinkedList类型WordPair(WordPair包含字符串wordA和wordB)进行排序,较小的可以正常工作,但是当我尝试使用数千个单词对列表进行排序时,如果每次都冻结失败了,这是我尝试过的第二种方法。我听说过垃圾收集,但不知道如何使用它,或者它是否会有所帮助。有谁知道如何在不改变数据类型的情况下提高这种方法的效率?

如果你运行这个你会注意到降序方法不起作用,我认为所有我要做的就是复制升序并交换两个大于或小于分区函数中的符号,但我猜不。所以,如果你能指出我正确的方向来解决这个问题,那将非常感激。

这是我的Quicksort课程......

import java.util.LinkedList;

public class Quicksort{

 private Partition p = new Partition();

public void sortAscending(LinkedList<WordPair> dictionary, int min, int max){
int pivot;

if(min < max){
  pivot = p.partitionAscending(dictionary, min, max);
  sortAscending(dictionary, min, pivot-1);
  sortAscending(dictionary, pivot+1, max);

  System.gc();
 }
}

public void sortDescending(LinkedList<WordPair> dictionary, int min, int max){
int pivot;

if(min < max){
  pivot = p.partitionDescending(dictionary, min, max);
  sortAscending(dictionary, min, pivot-1);
  sortAscending(dictionary, pivot+1, max);

  System.gc();
 }
}

public static void main(String[] args){

 }
}

和我的分区类......

import java.util.LinkedList;

public class Partition{

 public static int partitionAscending(LinkedList<WordPair> dictionary, int min, int max){
WordPair pivotpoint = dictionary.get(min);
int left = min;
int right = max;

while(left < right){
  while (dictionary.get(left).getWordA().compareToIgnoreCase(pivotpoint.getWordA()) <= 0 && left < right)
    left++;

  while (dictionary.get(right).getWordA().compareToIgnoreCase(pivotpoint.getWordA()) > 0)
    right--;

  if (left < right)
    swap(dictionary, left, right);

  System.gc();
}

swap(dictionary, min, right);

return right;
}

public static int partitionDescending(LinkedList<WordPair> dictionary, int min, int max){
WordPair pivotpoint = dictionary.get(min);
int left = min;
int right = max;

while(left < right){
  while (dictionary.get(left).getWordA().compareToIgnoreCase(pivotpoint.getWordA()) >= 0 && left < right)
    left++;

  while (dictionary.get(right).getWordA().compareToIgnoreCase(pivotpoint.getWordA()) < 0)
    right--;

  if (left < right)
    swap(dictionary, left, right);

  System.gc();
}

    swap(dictionary, min, right);

    return right;
  }

  private static void swap (LinkedList<WordPair> dictionary, int index1, int index2)
  {
    WordPair temp = dictionary.get(index1);
    dictionary.set(index1, dictionary.get(index2));
    dictionary.set(index2, temp);
  }

  public static void main(String[] args){

  }
}

0 个答案:

没有答案