Quote:
Originally Posted by DrPurdum
I forgot to comment on the code fragment you listed. I just checked the original code and it is the code you were able to compile. (I was also able to compile it with the new Visual Studio 2012 Express edition, which is the IDE used with the new book.) I'm not sure where the code you listed in the first section came from, but it is not the book's code. You may want to download the code for Chapter 12 again.
Dr. Purdum
|
I'm not sure what you mean by 'the code you were able to compile'. I agree that the swap method in listing 12-4 works fine, but the solution you offer makes the compiler unhappy.
The solution to chapter 12, exercise 4 reads:
The solution means that you must pass the data to be swapped into the method. One solution is:
Code:
private void swap01<T>(T[] data, int pos1, int pos2)
{
T temp;
temp = data[pos1];
data[pos1] = data[pos2];
data[pos2] = temp;
}
Now, as Swap01() gets called by:
Code:
public void quickSort(int first, int last)
{
int start; // Index for left partition
int end; // Index for right partition
start = first; // Keep copy of first element of array... 0
end = last; // ...and the last one- 99. (if 100 values)
if (last - first >= 1) // Make sure there's enough data to sort
{
int pivot = data[first]; // Set partitions- what if this is zero?
while (end > start) // While indexes don't match...
{ // Do left partition
while (data[start] /*first value*/ <= pivot && start <= last && end > start)
start++;
// Do right partition
while (data[end] > pivot && end >= first && end >= start)
end--;
if (end > start) // If right partition index smaller...
swap01(start, end); // ...do a swap
}
swap01(first, end); // Swap last element with pivot
quickSort(first, end - 1); // Sort around partitions
quickSort(end + 1, last);
}
else
{
return;
}
}
, intellisense informs us, understandably, that there is no method swap01 that takes only two arguments.
Additionally, in the swap method, we get the complaint that you cannot implicitly convert type 'T' to type 'int'.
This is where my confusion was. I'm not sure what adjustments to make as quicksort only returns two values, while swap01 expects three.