我有这个 Java algorithm 并且我遇到了麻烦 printing 解决排序所需的步骤数。这是代码
/* 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:
以显示 algorithm 以升序排列数组的步数。不是像现在这样的排序数组。例如,如果 algorithm 走了 30 步,我需要显示 Sorting was completed in: 30 Steps!
。我试过 printing class.display();
但它给了我一条错误消息。
请帮我。
谢谢你。
回答1
使用静态成员跟踪排序方法的调用,并在每次运行排序函数时将其递增一,如下所示
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);
}
}