, 나는 요소 비교 수를 계산해야합니다. 즉, 비교가 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);
}
}
은 for 루프 내부에서 계산하지 않을 것이며, 비교가 아닌 교환 수입니다. –
@ GrantClark 내 대답을 업데이트했습니다. – freedev