我有這個 Java 演算法,我無法列印解決排序所需的步驟數。這是代碼
/* The main function that implements QuickSort()
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
static void sort(int arr[], int low, int high)
{
if (low < high)
{
/* partIndex is partitioning index, arr[partIndex] is
now at right place */
int partIndex = partition(arr, low, high);
// Recursively sort elements before
// partition and after partition
sort(arr, low, partIndex-1);
sort(arr, partIndex 1, high);
}
}
/* print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i)
System.out.print(arr[i] " ");
System.out.println();
}
// Driver Code
public static void main(String args[])
{
int[] data = {12,9,4,99,120,1,3,10,23,45,75,69,31,88,101,14,29,91,2,0,77};
System.out.println("Unsorted Array \n" " ");
System.out.print(Arrays.toString(data) "\n");
int n = data.length;
RandomQuicSort.sort(data, 0, n - 1);
//sort(data, 0, n-1);
System.out.println("Sorted array in ascending order");
System.out.println(Arrays.toString(data) "\n");
System.out.println("Sorting was completed in: " );
printArray(data);
}
}
這是輸出。
Unsorted Array
[12, 9, 4, 99, 120, 1, 3, 10, 23, 45, 75, 69, 31, 88, 101, 14, 29, 91, 2, 0, 77]
9 Was swapped with 120
1 Was swapped with 9
0 Was swapped with 1
3 Was swapped with 10
9 Was swapped with 10
23 Was swapped with 101
23 Was swapped with 75
14 Was swapped with 23
69 Was swapped with 77
31 Was swapped with 75
31 Was swapped with 45
91 Was swapped with 120
101 Was swapped with 120
Sorted array in ascending order
[0, 1, 2, 3, 4, 9, 10, 12, 14, 23, 29, 31, 45, 69, 75, 77, 88, 91, 99, 101, 120]
Sorting was completed in:
0 1 2 3 4 9 10 12 14 23 29 31 45 69 75 77 88 91 99 101 120
我想更改最后一行Sorting was completed in:以顯示演算法將陣列按升序排列所采取的步驟數。不是像現在這樣的排序陣列。例如,如果演算法需要 30 步,我需要顯示Sorting was completed in: 30 Steps!. 我試過列印class.display();,但它給了我一條錯誤訊息。
請幫我。
謝謝你。
uj5u.com熱心網友回復:
使用靜態成員跟蹤排序方法的呼叫,并在每次運行排序函式時將其遞增一,如下所示
class RandomQuicSort
{
// This Function helps in calculating
// the inclusive high and low
public static int stepsToSort = 0;
static void random(int arr[],int low,int high)
然后在你的排序方法結束時像這樣遞增它
static void sort(int arr[], int low, int high)
{
if (low < high)
{
/* partIndex is partitioning index, arr[partIndex] is
now at right place */
int partIndex = partition(arr, low, high);
// Recursively sort elements before
// partition and after partition
stepsToSort ;
sort(arr, low, partIndex-1);
sort(arr, partIndex 1, high);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/475523.html
上一篇:反向陣列查詢
