[英]Counting number of comparisons in shell sort
使用此代碼,我必須計算進行元素比較的次數。 話雖如此,我不確定比較是在sort()方法的for循環內還是在less()方法內完成。 非常感謝你的幫助。
public class Shell {
private static int compares;
// This class should not be instantiated.
private Shell() { }
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
int n = a.length;
// 3x+1 increment sequence: 1, 4, 13, 40, 121, 364, 1093, ...
int h = 1;
while (h < n/3) h = 3*h + 1;
while (h >= 1) {
// h-sort the array
for (int i = h; i < n; i++) {
for (int j = i; j >= h && less(a[j], a[j-h]); j -= h) {
exch(a, j, j-h);
}
}
assert isHsorted(a, h);
h /= 3;
}
assert isSorted(a);
}
/ ******************* ************************** *幫助程序排序功能。 ************************************************** ******** /
// is v < w ?
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
// exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
/ ******************* ************************** *檢查數組是否已排序-對調試很有用。 ************************************************** ************************ /
private static boolean isSorted(Comparable[] a) {
for (int i = 1; i < a.length; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
// is the array h-sorted?
private static boolean isHsorted(Comparable[] a, int h) {
for (int i = h; i < a.length; i++)
if (less(a[i], a[i-h])){
return false;
}
return true;
}
// print array to standard output
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
/**
* Reads in a sequence of strings from standard input; Shellsorts them;
* and prints them to standard output in ascending order.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
Shell.sort(a);
show(a);
}
}
假設您的代碼看起來像經典學生的練習,那么可能會要求您僅對在sort
函數內調用的less
函數進行的元素比較次數進行計數。 如果我錯了,請更新您的問題,並添加對目標的更完整描述。
如您所見,每次調用less
函數時都會進行比較。 但是在您的代碼段中,甚至less
的甚至是比較兩個對象的常用方法。 因此,僅當在sort
方法中直接調用less
函數時,才應計數。 其他情況isSorted
和isHsorted
僅存在於斷言中。
為了清楚起見,斷言是Java編程語言中的一條語句,它使您能夠測試有關程序的假設。
記住,這是您的練習,所以您不應該四處尋找簡單的答案,並且我不會編寫任何詳細的代碼解決方案。
但是我可以給您另一個建議,您可以嘗試創建一個新方法lessWithCounter
,以less
名義被調用到sort
方法中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.