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.

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
#include <stdio.h>

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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) && (left<right)) left++; 
    while ((strcmp(theEmps[right].lastname,pivot)>0) && (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.