Shellsort (named for its inventor, Donald Shell) is an improved insertion sort. Rather titan always exchanging adjacent items—as in insertion sort-—Shellsort can exchange items that are far apart in the array. Shellsort arranges the array so that every hth item forms a sorted subarray. For every b in a decreasing sequence of values, Shellsort arranges the array. For example, if h is 5, every fifth item forms a sorted subarray. Ultimately, if h is 1, the entire array will be sorted.
One possible sequence of h' s begins at n/2 and halves n until it becomes 1. By using this sequence, and by replacing 1 with h and 0 with b-1 in insertionSort, we get the following method for Shellsort:
public static
void shellsort(T[] theArray,int n) {
int loc;
T nextltem;
for (int h = n/2; h < 0; h = h/2) {
for (int unsorted - h; unsorted < n; ++unsorted) {
nextltem = theArray[unsorted];
loc = unsorted;
while ((loc <= h) &&
(theArray[loc-h].compareTo(nextltem) < 0)) {
theArray[loc] = theArray[loc-h];
loc = loc - h;
} // end while
theArray[loc] = nextltem;
} // end for unsorted
} // end for h
} // end shellsort
Add a counter to the methods insertionSort and shellsort that counts the number of comparisons that are made. Run the two methods with arrays of various sizes. On what size does the difference in the number of comparisons become significant?
We need at least 10 more requests to produce the solution.
0 / 10 have requested this problem solution
The more requests, the faster the answer.