QuickSort не работает на ходу? - PullRequest
0 голосов
/ 07 октября 2018

Для проекта мой код должен запускать два алгоритма сортировки с одним и тем же списком несортировки.Несортированный список - это массив, заполненный случайными целыми числами.Я запустил свой код и один из двух методов сортировки работает.Метод быстрой сортировки не отображается при запуске кода.Я попробовал другой способ и получаю код ошибки

| Метод quickSort (int [], int, int) в тесте типа не применим для аргументов (Class, int, int).|

Любая причина, по которой моя быстрая сортировка не отображается, когда я запускаю свой код.Вот часть моего кода.

public static void main (String [] args) {
    Random generator = new Random();
    int [] unsort= new int [100];
    //creates an array of a 100 objects

    for(int i = 0;i < unsort.length; i++) {
        unsort[i] = generator.nextInt(99)+1;
    }
    // fills the array with 100 random numbers


    System.out.println("unsorted :"+Arrays.toString(unsort);
    Quicksort(unsort,0,unsort.length-1);
    System.out.println("quicksort:"+ Arrays.toString(unsort));
    //goes to each sorting method and run the sorting program
}

 public static void Quicksort(int[] unsort, int low, int high) {
     if (low >= high && unsort.length==0){
            return;  
     }
     //Checks if the array is already sorted or empty, it will return the array


    int i= low;
    int j = high;
    //creates a smaller reference to use in the if/while statements

    int pivot = unsort[i+(j-i)/2];
    //the pivot is middle value of the array 


    while(i<=j ) {
        while( unsort[i]< pivot) {
            i++;
        }
        while(unsort[i]>pivot) {
            j--;
        }
        // while statements keeps all numbers less than the pivot to the low bounds
        //and all the numbers higher than the pivot to the right

        if(i<=j) {
            int temp = unsort[i];
            unsort[i]= unsort[j];
            unsort[j]=temp;
            i++;
            j--;
            //comparisons++;
        }
        //if the selected object is bigger than the object in the low bound
        // It will swap the placement of both numbers

        if(low<j) Quicksort(unsort,low,j);

        if (i< high) Quicksort(unsort,i,high);

        // its the recursive method to keep all the high and low numbers in their bounds

    }
}

1 Ответ

0 голосов
/ 07 октября 2018

Полагаю, это из-за того, что Java передается по значению, а вы не возвращаете, поэтому изменения не отражаются обратно в несортированном [].

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...