Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Change this quicksort to a median-of-three quicksort. HELP!

Status
Not open for further replies.

eelsar

Technical User
May 20, 2002
36
US
How would I change the following code from working with the pivot as the first element, to a median-of-three pivot.

I tried a few ways and I was unsuccessful.
I would appreciate if someone can show me.
Thank you!

void Sort::quickSort(Card cardArray[], int first, int last)
{
int pivotPosition; //final position of pivot
if(first < last)//more than one element in the list
{
//split into 2 sublists
split(cardArray,first,last,pivotPosition);
//sort left sublist
quickSort(cardArray,first,pivotPosition-1);
//sort right sublist
quickSort(cardArray,pivotPosition+1, last);

}

//else list has 0 or 1 element and requires no sorting

}


void Sort::split(Card cardArray[],int first, int last, int& position)
{
int count=0;
int left = first; //index for left search
int right = last; //index for right search
Card pivot = cardArray[first]; //pivot element
Card temp;

while(left < right)
{

//Search from left for element > pivot
while(cardArray
.suitNum >pivot.suitNum)
{
right--;
}
//Search from right for element <= pivot
while(left < right && cardArray
.suitNum <=pivot.suitNum)
{

left++;

}

//Interchange elements if searches haven't met
if(left < right)
{

temp = cardArray
;
cardArray
= cardArray
;
cardArray
= temp;
}

else
{
position = right;
cardArray[first] = cardArray[position];
cardArray[position] = pivot;
}

}


}​
 
Change the line in split()

Card pivot = cardArray[first];

to

Card pivot = cardArray[(last-first)/2];
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top