quicksort

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
typedef struct Emp 
{
  unsigned char lname[MaxName + 1]; /* + 1 for '\0' */
  unsigned char fname[MaxName + 1];
  unsigned int  id;
  unsigned char dept;
  bool married;
} Emp;
    
int comp1(const void* item1, const void* item2) 
{
  const Emp* emp1 = (const Emp*) item1;  //emp1 points to Emp
  const Emp* emp2 = (const Emp*) item2; 
  unsigned char buff1[BuffSize];
  unsigned char buff2[BuffSize];
   	
  strcpy(buff1, emp1->lname);
  strcat(buff1, emp1->fname);
  strcpy(buff2, emp2->lname);
  strcat(buff2, emp2->fname);
   	
  return strcmp(buff1, buff2);
}
   	
int comp2(const void* item1, const void* item2) 
{
  const Emp** emp1 = (const Emp**) item1; // pointer to pointer to Emp
  const Emp** emp2 = (const Emp**) item2;
  unsigned char buff1[BuffSize];
  unsigned char buff2[BuffSize];
  strcpy(buff1, (*emp1)->lname);
  strcat(buff1, (*emp1)->fname);
  strcpy(buff2, (*emp2)->lname);
  strcat(buff2, (*emp2)->fname);
  return strcmp(buff1, buff2);
}

/* 1st qsort: better or worse approach than 2nd? why? emps here is an array*/
qsort(emps, n, sizeof(Emp), comp1);
   
/* 2nd qsort: better or worse approach than 1st? why? 
   Emp* emps_a[6] */
   qsort(emps_a, n, sizeof(Emp*), comp2);
   


Based on the above code, which is the better quicksort and why?

thanks, this really has me in a bind....:(
Last edited on
The first, because the 2nd has to dereference the doubt-pointer to access the pointer. There is no need for this and it just takes a tiny bit more time.

Also, strcpy is bad, so neither would be ideal. Should be using strncpy. The declaration of your buffer should also be initialised to {0}.
Zaita,

I figured so, but wanted to be extra sure. Thanks for the input.
Topic archived. No new replies allowed.