Hi all, I am starting to understand how recursion works, but there are still
spots I am unsure, here is the code I have so far, the problems I have are:
1)how do I indicate last index when I call: quicksort(list, pivot+1, /*END of list*/) for partitioning upper sublist
2)for the 2 elems base case, how do I know what their indices are
3)for the conquer stage, how do I know the indices to add each merged list
from each recursive level call to a new final array?
4) is returning the list in the two base cases I have correct?
Any pointers (no pun intended) would be appreciated!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
#include <iostream>
using namespace std;
//NB: need start and end to determine where to divide each level's lower and
// upper sublist
int *quickSort(int *list, int start, int end)
{
int pivot;//set it to first index for each L,R sublist and for original list
int smallIndex;//points to last elem in lower sublist
int size = sizeof(list)/sizeof(int);
//partition
//determine pivot position first
pivot = start;
smallIndex = pivot;//end index of lower sublist initialized to pivot's index
//Base case: 2 elems (just sort by swapping if needed and return list?)
if ( size == 2 )
{
//*Q: what are the indices to compare elems?
if ( /*HOW DO I KNOW INDICES TO COMPARE THE 2 elems*/ )//IF elems not sorted, swap
{
/**NEED ASSISTANCE HERE!*/
}
return list;
}
//Base case: 1 elem (already sorted and return list)
else if ( size == 1 )
return list;
//if more than 2 elems in cur level (recursive call) sublist then
// partition
else if ( size > 2 )
{
for ( int i = 0; i < size; i++ )//iterate cur level's sublist
{
if ( list[i] < list[pivot] )//"add" cur item to lower sublist
{
smallIndex+=1;//mov smallIndex forwrd by 1 to "grow" lower sublist
int temp = list[smallIndex];//hold val > pivot to mov to list end
list[smallIndex] = list[i];//mov val < pivot to front of list
list[i] = temp;
}
}
//now mov pivot to its proper place(=>swap pivot w/ smallIndex)
// & update indx pivot
int holder = list[pivot];
list[pivot] = list[smallIndex];
list[smallIndex] = holder;
pivot = smallIndex;//update indx pivot
//recursive call for partitioning lower sublist
quickSort(list,0,pivot - 1);
//recursive call for partioning upper sublist
quickSort(list,pivot + 1,/*END index of sublist*/);
}
}//END quickSort
|