Need help on this Quick Sort function

Hello all, I know there are tons of quickSort algorithm out there already, however, I tried couple of them, none of them gave me the correct result and I couldn't figure out where the bug is. =[

The function is for sorting name strings, I used strcmp for that.
Is that because I can't swap inside vector? Or something else?

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
54
55
56
57
58
59
60
61
62

  struct Students
{
  string ID;
  string lastName;
  string firstName;
  string level;
};

class RosterClass
{
public:
  vector<Students> student;
  void print();
  
  //quickSort
  void quickSort(int , int);

};


 void RosterClass::quickSort(int start, int end)
{
  //s = starting index
  //e = ending index

 // if (start >= end) return; // done! 
  string pivot = student[(start + end) / 2].firstName;
  int left = start; // index of left-most element 
  int right = end; // index of right-most element
 
  do
  {
    while (myStriCmp(student[left].firstName, pivot) < 0)//left < pivot
      left++;
    while (myStriCmp(pivot, student[right].firstName) < 0)//pivot < right
      right--;
    if (left <= right)
    {
      Students temp = student[left];
      student[left] = student[right];
      student[right] = temp;
      left++;
      right--;
    }
  }while (left <= right);

  if (start < right)
    quickSort(start, right);
  if (left < end)
    quickSort(left, end);

}

//reference functions
int myStriCmp(string d, string s)
{
  char* dst = new char[d.length() + 1];
  char* src = new char[s.length() + 1];

  return strcmp(dst, src);
}


Any help would be appreciate!
Last edited on
1
2
3
4
5
6
7
int myStriCmp(string d, string s)
{
  char* dst = new char[d.length() + 1];
  char* src = new char[s.length() + 1];

  return strcmp(dst, src);
}
Tou do know that std::string already has comparsion operator, right?

1) Your function contains a leak. dst and src are not freed after creation.
2) Values of dst and src arrays are ininitialized, so for all purposes essentually random.
Thanks! I misunderstood the use of string.compare (), that wasted me so much time...
Thank you very much for the help.
YOu can compare strings as simply as
1
2
3
4
std::string d = /*...*/;
std::string s = /*...*/;
if ( d == s ) {
    //... 
hmmm...can I just use

1
2
3
string a;
string b;
if (a > b)
directly without overload operator?
Yes, you can.
Topic archived. No new replies allowed.