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
|
//the quicksort
#include <iostream>
#include <cstring>
using namespace std;
void quicksort(char *items, int len);
void qs(char *items, int left, int right);
int main()
{
char str[] = "jfmckldoelazlkper";
cout << "Original order: " << str <<'\n';
quicksort(str, strlen(str)); //call the function to sort the string (character sort)
cout << "sorted order: " << str << '\n';
return 0;
}
//set up the call to the actual sorting function
void quicksort(char *items, int len)
{
qs(items, 0, len-1);
}
// A recursive version of Quicksort for sorting characters
void qs(char *items, int left, int right)
{
int i, j;
char x, y;
i = left; j = right;
x = items[( left+right) / 2 ];
do{
while((items[i] < x) && (i < right)) i++;
while((x < items[j]) && (j > left)) j--;
if(i <= j){
y = items[i];
items[i] = items[j];
items[j] = y;
i++; j--;
}
}while(i <= j);
if(left < j) qs(items, left, j);
if(i < right) qs(items, i, right);
}
|