2015-10-15 16 views
-1

我想实现快速排序来根据它们的长度来排序字符串。我在做什么是错的,我不能为我的生活找出什么是不正确的。我希望另一组眼睛可以检查我的代码并找出我出错的地方。如何将QuickSort集成到一个字符串向量中,我必须对字符串的长度进行排序?

void justAQuickieSort(int left, int right) 
{ 
//left and right given by left = 0 and right = copy.begin(); 
    if(left < right) 
    { 
    int part = partition(left, right); 
    justAQuickieSort(left, part - 1); 
    justAQuickieSort(part + 1, right); 
    } 
} 

int partition(int left, int right) { 

    string temp = " "; 
    const int mid = left + (right - left)/2; 

    // move the mid point value to the front. 

    temp = copy[mid]; 
    copy[mid] = copy[left]; 
    copy[left] = temp; 
    int i = left + 1; 
    int j = right; 
    while (i <= j) { 

     while(i <= j && copy[i].size() <= copy[mid].size()) { 
      i++; 
     } 

     while(i <= j && copy[j].size() > copy[mid].size()) { 
      j--; 
     } 

     if (i < j) { 
      cout << "here" << endl; 
      temp = copy[i]; 
      copy[i] = copy[j]; 
      copy[j] = temp; 
     } 
    } 
    temp = copy[i-1]; 
    copy[i-1] = copy[left]; 
    copy[left] = temp; 
    return i-1; 

感谢您给予的任何帮助。

+0

一些建议:如果你要写你自己的排序,我建议你写一个模板版本,根据给出的类型进行排序。一旦你这么做了(比如用简单的'int'类型),将进行比较的部分分解为一个单独的函数,该函数接受两个参数,并根据arg1 PaulMcKenzie

+0

@PaulMcKenzie如果我确实这样做了,那么我会在哪里把它放在我的快速排序中? – terrabl

回答

0

一个错误是在这里:

while(i <= j && copy[i].size() <= copy[mid].size()) { 
    i++; 
} 

while(i <= j && copy[j].size() > copy[mid].size()) { 
    j--; 
} 

你尽管被感动“中”到“左”与“中”比较应该是

while(i <= j && copy[i].size() <= copy[left].size()) { 
    i++; 
} 

while(i <= j && copy[j].size() > copy[left].size()) { 
    j--; 
}