### Sorting Strings with Quicksort

How would I make this code work? Quicksort usually sort integers, but I want it to sort the lastname of the employees.

 ``12345678910111213141516171819202122232425262728293031323334353637`` ``````#include typedef struct EmpRecord { char lastname[15]; char firstname[15]; char fullname[30]; }EmpRecord; void qsort(int table,int start,int finish); int main(void) { EmpRecord theEmps; qsort(theEmps,0,4); return 0; } void qsort(EmpRecord theEmps,int start,int finish) { int left=start, right=finish, pivot=theEmps[(start+finish)/2]; while (left < right) { while (theEmps[left].lastname < pivot) left++; while (theEmps[right].lastname > pivot) right--; if (left <= right) { int temp = theEmps[left].lastname; theEmps[left].lastname = theEmps[right].lastname; theEmps[right].lastname = temp; left++; right--; } } if (start < right) qsort(theEmps,start,right); if (left < finish) qsort(theEmps,left,finish); } ``````
 Quicksort usually sort integers
quicksort actually sorts anything you can provide comparsion function for. Look how qsort implemented in C: In takes an array, size of single element and array size (due to not having runtime type information) and pointer to comparsion function.
TL;DR: either use std::string in your struct (so comparsion operators will work) or use strcmp instead of < and >
quicksort can sort any two data types which can be compared with each other.
But in your code you have use the comparison
theEmps[left].lastname < pivot
which won't work . Because the call "theEmps[left].lastname" will give the ASCI of lastname which will be definitely not less than pivot so it wont work that way.
Thanks, I used strcmp to compare them and it worked.
 ``123456789101112131415161718`` ``````void qsort(EmpRecord theEmps[5],int start,int finish) { int left=start, right=finish; char * pivot=theEmps[(start+finish)/2].lastname; while (left < right) { while ((strcmp(theEmps[left].lastname,pivot)<0) && (left0) && (right>left)) right--; if (left <= right) { EmpRecord temp = theEmps[left]; theEmps[left] = theEmps[right]; theEmps[right] = temp; left++; right--; } } if (start < right) qsort(theEmps,start,right); if (left < finish) qsort(theEmps,left,finish);``````
Last edited on
Topic archived. No new replies allowed.