2016-11-09 7 views
-2

Я создал метод для быстрого алгоритма сортировки с использованием дженериков, я пытаюсь реализовать этот метод, но я пытаюсь реализовать так, чтобы он быстро сортировал любые переменные с массивом, такие как числа, строка, символ и т. д. Я реализовал этот класс.Как решить общую ошибку в java

это мой класс AssertRayTool.

package arraySorter; 

import RandomArray.RandomArray; 


public abstract class ArraySortTool<T extends Comparable<T>> implements ArraySort<T> 
{ 

    private double timeTakenMillis(T[] array) { 
     double startTime = System.nanoTime(); 
     sort(array); 
     return ((System.nanoTime()-startTime)/1000000.0); 
    } 


    public void timeInMillis(RandomArray<T> generator,int noPerSize,int maxTimeSeconds) 
    { 
     int size = 1; // initial size of array to test 
     int step = 1; // initial size increase 
     int stepFactor = 10; // when size reaches 10*current size increase step size by 10 
     double averageTimeTaken; 
     do { 
      double totalTimeTaken = 0; 
      for (int count = 0; count < noPerSize; count++) { 
       T[] array = generator.randomArray(size); 
       totalTimeTaken += timeTakenMillis(array); 
      } 
      averageTimeTaken = totalTimeTaken/noPerSize; 
      System.out.format("Average time to sort %d elements was %.3f milliseconds.\n",size,averageTimeTaken); 
      size += step; 
      if (size >= stepFactor*step) step *= stepFactor;   
     } while (averageTimeTaken < maxTimeSeconds*1000); 
     System.out.println("Tests ended."); 
    } 


    public boolean isSorted(T[] array) { 
     int detectedDirection = 0; // have not yet detected increasing or decreasing 
     T previous = array[0]; 
     for (int index = 1; index < array.length; index++) { 
      int currentDirection = previous.compareTo(array[index]); // compare previous and current entry 
      if (currentDirection != 0) { // if current pair increasing or decreasing 
       if (detectedDirection == 0) { // if previously no direction detected 
        detectedDirection = currentDirection; // remember current direction 
       } else if (detectedDirection * currentDirection < 0) { // otherwise compare current and previous direction 
        return false; // if they differ array is not sorted 
       } 
      } 
      previous = array[index]; 
     } 
     // reached end of array without detecting pairs out of order 
     return true; 
    } 

    public void sort(T[] array) { 
     // TODO Auto-generated method stub 

    } 
} 

это мой класс Quicksort, который расширяет класс выше.

package arraySorter; 

public class QuickSort<T extends Comparable<T>> extends ArraySortTool<T> 


{ 
    private T array[]; 
    private int length; 

    public void sort(T[] array) { 

     if (array == null || array.length == 0) { 
      return; 
     } 
     this.array = array; 
     length = array.length; 
     quickSort(0, length - 1); 
    } 

    private void quickSort(int lowerIndex, int higherIndex) { 

     int i = lowerIndex; 
     int j = higherIndex; 
     // calculate pivot number, I am taking pivot as middle index number 
     int pivot = [lowerIndex+(higherIndex-lowerIndex)/2]; 
     // Divide into two arrays 
     while (i <= j) { 

      while (array[i] < pivot) { 
       i++; 
      } 
      while (array[j] > pivot) { 
       j--; 
      } 
      if (i <= j) { 
       exchangeValues(i, j); 
       //move index to next position on both sides 
       i++; 
       j--; 
      } 
     } 
     // call quickSort() method recursively 
     if (lowerIndex < j) 
      quickSort(lowerIndex, j); 
     if (i < higherIndex) 
      quickSort(i, higherIndex); 
    } 

    private void exchangevalues(int i, int j) { 
     int temp = array[i]; 
     array[i] = array[j]; 
     array[j] = temp; 
    } 

} 
+0

И вопрос/проблема есть? – UnholySheep

+0

Возможно, попробуйте [edit] ing в более подробной информации? Я понятия не имею, какой вопрос даже здесь. Добавьте некоторые ошибки/стеки и подробное объяснение того, что вы ожидаете, и того, что вы испытываете. _voting для закрытия из-за отсутствия context_ –

ответ

1

Из того, что я вижу, вы обрабатываете свой общий массив только как массив целых чисел. Чтобы исправить это

int pivot = [lowerIndex+(higherIndex-lowerIndex)/2]; 

Становится

T pivot = [lowerIndex+(higherIndex-lowerIndex)/2]; 

И

while (array[i] < pivot) 
    i++; 

while (array[j] > pivot) { 
    j--; 

Становится

while (array[i].compareTo(pivot) < 0) 
    i++; 

while (array[j].compareTo(pivot) > 0) 
    j--; 

Кроме того, не забывайте, что ваш T класс должен реализовать Сопоставимые, в противном случае вам не смогут сравнивать объекты ,

+0

Благодарим вас за комментарии быстрый вопрос –