I have this quick sort implementation to sort the characters.
int main(){
char val[] = "dcbeaaae";
QuickSort(val, 0, length);
for(int i=0;i<length;i++) //Sorted print
cout<<val[i];
return 0
}
void QuickSort(char values[], int first, int last)
{
if(first<last)
{
int splitPoint;
Split(values, first, last, splitPoint);
QuickSort(values, first, splitPoint-1);
QuickSort(values, splitPoint+1, last);
}
}
void Split(char values[], int first, int last, int& splitPoint)
{
int splitVal = values[first];
int saveFirst = first;
bool onCorrectSide;
first++;
do
{
onCorrectSide = true;
while(onCorrectSide)
{
if(values[first] > splitVal)
onCorrectSide = false;
else
{
first++;
onCorrectSide = (first<=last);
}
}
onCorrectSide = (first<=last);
while(onCorrectSide)
if(values[last] <= splitVal)
onCorrectSide = false;
else
{
last--;
onCorrectSide = (first<=last);
}
if(first<last)
{
Swap(values[first], values[last]);
first++;
last--;
}
}while(first<=last);
splitPoint = last;
Swap(values[saveFirst], values[splitPoint]);
}
void Swap(char& item1, char& item2)
{
char temp = item1;
item1 = item2;
item2 = temp;
}
However, the output that I get from this is a bit wrong i.e I get an additional space in the starting of these sorted characters. On putting a breakpoint, I saw that at index 0, the element is = 0
Input: aaabcdee
Output: aaabcdee (one additional space before the first a )
Any suggestions what I am missing out here?
Assuming
lengthis the number of characters (excluding the NUL char) in the character array. You need to call the quicksort function as:because the last argument to the function
QuickSortis the index of the last element of the array and in a character array of lengthlengththis index islength - 1.By passing
lengthto the function you are making even the NUL character participate in the sorting and as it is smaller than other characters it gets moved to the beginning of the sorted array which gets printed as a blank when printed.