Quicksort with strings

I know that quicksort sorts integers, but can it also sort strings? For example, can I quicksort sort an array of fruits with members: oranges, apples, watermelons, and pears? If you could, how would you go about doing so.
Quick sort is an algorithm which can sort anything you can define strict weak ordering of. If you are asking about function from C standard library, you can sort anything if you provide custom comparator function ( http://en.cppreference.com/w/cpp/algorithm/qsort ). However it is better to use std::sort algorithm ( http://en.cppreference.com/w/cpp/algorithm/sort ). It is more type safe and easier to use.
This is only a snippet of the program. Is this sort correct way to go about quicksorting the last name of the students?

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
typedef struct Student
{
     char firstname,lastname,fullname;
     float t1,t2,t3;
}Student;

const int MAXSTUDENTS = 5;
void qsort(Student theStu[],int first,int last);

int main (void)
{
struct Student theStu;
qsort(theStu[],0,MAXSTUDENTS - 1);
}

void qsort(Student theStu,int start,int finish)
{
  int left=start,
      right=finish,
      pivot=theStu.lastname[(start+finish)/2];
  while (left < right) {
    while (theStu.lastname[left]  < pivot) left++; 
    while (theStu.lastname[right] > pivot) right--; 
    if (left <= right) {
      int temp = theStu.lastname[left];
      theStu.lastname[left] = theStu.lastname[right];
      theStu.lastname[right] = temp;
	  left++;
  	  right--;
    } 
  } 
  if (start < right) qsort(theStu,start,right);
  if (left < finish) qsort(theStu,left,finish);
}
umm... if u want to sort fruits in alphabetical order, this is one way using vectors:


#include<iostream>
#include<conio.h>
#include<vector>
#include<algorithm>
#include<ctime>
#include<cstdlib>

using namespace std;

int main()
{
vector<string>fruits ;
vector<string>:: const_iterator iter;
vector<string> :: const_iterator myiter;
fruits.push_back("pear");
fruits.push_back("apples");
fruits.push_back("watermelon");

srand(static_cast<unsigned int>(time(0)));


random_shuffle(fruits.begin(),fruits.end());

for(iter=fruits.begin();iter!=fruits.end();iter++)
{
cout<<*iter<<endl;
}

cout<<"sorted list \n";
sort(fruits.begin(),fruits.end());

for(myiter=fruits.begin();myiter!=fruits.end();myiter++)
{
cout<<*myiter<<endl;
}

getch();
}

Topic archived. No new replies allowed.