Where to put ShellSort Comparisons and Exchanges Counter? In java, I have: publi
ID: 3669202 • Letter: W
Question
Where to put ShellSort Comparisons and Exchanges Counter?
In java, I have:
public class Sort {
static int exchanges= 0;
static int comparisons= 0;
public static void SegmentedInsertionSort (AnyType[] array, int N, int gap)
{
for (int index = gap ; index < N ; index++)
{
AnyType temp;
int j = index - gap;
comparisons++;
while (j >= 0)
{
comparisons++;
if (array[j].isBetterThan(array[j+gap]))
{
temp = array[j];
array[j] = array[j + gap];
array[j + gap] = temp;
j = j - gap;
exchanges++;
}
else j = -1;
}
}
public static void shellSort (AnyType[] array)
{
int N = 2000;
int gap = N/2;
while (gap > 0)
{
SegmentedInsertionSort(array, N, gap);
gap = gap / 2;
}
}
}
But I'm not getting the data I expected. Where should my counters go?
Explanation / Answer
The modified code will be as follows:
public class Sort {
static int exchanges= 0;
static int comparisons= 0;
public static void SegmentedInsertionSort (AnyType[] array, int N, int gap)
{
for (int index = gap ; index < N ; index++)
{
AnyType temp;
int j = index - gap;
while (j >= 0)
{
if (array[j].isBetterThan(array[j+gap]))
{
temp = array[j];
array[j] = array[j + gap];
array[j + gap] = temp;
exchanges++;
j = j - gap;
} //end of if
else
j = -1;
comparisons++;
} //end of while
} // end of method
public static void shellSort (AnyType[] array)
{
int N = 2000;
int gap = N/2;
while (gap > 0)
{
SegmentedInsertionSort(array, N, gap);
gap = gap / 2;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.