排序,同时保持重复

时间:2014-12-01 13:38:52

标签: c++ sorting vector duplicates

我有三个载体

vector<string> a_words0(75000);
vector<string> a_words1(75000);
vector<string> a_words2(75000);

请考虑以下元素在同一行中的外观:

.
.
.
It's    raining  outside
The     warrior  is
It's    raining  heavily
It's    raining  outside
.
.
.

我正在使用quicksort函数根据第一个向量进行排序,它给了我以下结果

.
.
.
It's    raining  outside
It's    raining  heavily
It's    raining  outside
The     warrior  is
.
.
.

问题是我希望副本像这样:

.
.
.
It's    raining  outside
It's    raining  outside
It's    raining  heavily
The     warrior  is
.
.
.

这是我的快速排序功能:

void quicksort(vector<string> &arr0, vector<string> &arr1,vector<string> &arr2,int low, int high)
{
int i = low;
int j = high;
string y = "Z";
/* compare value */
string z = arr0[(low + high) / 2];

/* partition */
do {
    /* find member above ... */
    while(arr0[i] < z) i++;

    /* find element below ... */
    while(arr0[j] > z) j--;

    if(i <= j) {
        /* swap two elements */
        y = arr0[i];
        arr0[i] = arr0[j]; 
        arr0[j] = y;
        y = arr1[i];
        arr1[i] = arr1[j]; 
        arr1[j] = y;
        y = arr2[i];
        arr2[i] = arr2[j]; 
        arr2[j] = y;
        i++; 
        j--;

    }
} while(i <= j);


/* recurse */
if(low < j) 
    quicksort(arr0,arr1,arr2, low, j);

if(i < high) 
    quicksort(arr0,arr1,arr2, i, high); 
}

1 个答案:

答案 0 :(得分:1)

您可以更改比较以比较arr0的两个元素,如果相同,则比较arr1的两个元素,如果仍然相同,则比较arr2的两个元素。您可以考虑将Y的名称更改为T(对于temp),然后使用X,Y,Z作为arr0,arr1和arr2的轴心点。

快速排序不稳定,因此您无法使用从最不重要到最重要的多次排序。您可以使用std :: stable_sort()(通常实现为合并排序),并再次使用自定义比较,比较arr0,arr1和arr2(如果需要),或者将数据排序3次,首先是arr2,然后是arr1,然后是arr0。