合并排序结构不起作用

时间:2013-10-06 00:42:15

标签: c++ struct mergesort

我正在对结构执行合并排序。 排序在作为数组的目标城市上执行 当我尝试使用普通数组时,它可以工作。但它不适用于结构:(

#include <fstream>   // for std::ifstream
#include <sstream>   // for std::istringstream
#include <cstring>    // for std::string and std::getline
#include <iostream>
#include <ctype.h>
#include <stdio.h>
#include<algorithm>
#include <string.h>

using namespace std;

#define MAX 30
#define WORD 3


typedef struct node{
int nodeId;
char destCity[MAX];
char arrCity[MAX];
int time;
}NODE;

typedef struct edge{
 int adjoin;
int distance;
}EDGE;

typedef struct graph{
NODE cityNode[MAX];
EDGE e[MAX][MAX];
}GRAPH;

GRAPH graph,graphCpy,Temp;
GRAPH currentArray;


void MergeA(int low ,int mid , int high)
{
int i = low, j = mid+1 , k = low;

while(i <= mid && j <= high)
{
    if(currentArray.cityNode[i].destCity <= currentArray.cityNode[j].destCity)
    {
    strcpy(Temp.cityNode[k].destCity,currentArray.cityNode[i].destCity);
            i++;
    }
    else
    {
            strcpy(Temp.cityNode[k].destCity,currentArray.cityNode[j].destCity);
        Temp[k].assign(currentArray[j]);
            j++;
    }
    k++;
}
if(i > mid )
{
    for(int h = j ;h <= high ; h++ )
    {

    strcpy(Temp.cityNode[k].destCity,currentArray.cityNode[h].destCity);
        k++;

    }
}
else
    for(int h = i; h<= mid ; h++ )
    {

strcpy(Temp.cityNode[k].destCity,currentArray.cityNode[h].destCity);

    k++;

    }
 for(int i = low; i <= high ; i++){

    strcpy(currentArray.cityNode[i].destCity,Temp.cityNode[i].destCity);
}


}
void MergeSortA(int low , int high)
{

int mid = 0;
if(low < high)
{
    mid = low + (high-low)/2;
cout<<"beforemerge"<<endl;
    MergeSortA(low , mid);
    MergeSortA(mid+1,high);
    MergeA(low,mid,high);

}
}
int main(){
std::ifstream infile("theWords.txt");
    std::string line;
while (std::getline(infile,(line)) && count<30){
    std::istringstream iss(line);
            if ((iss) >>graph.cityNode[count].destCity >> graph.cityNode[count].arrCity  >> graph.cityNode[count].time){
graph.cityNode[count].nodeId = count ;
count++;
}
graphCpy= graph;
currentArray= graphCpy;
MergeSortA(0,count);
for(int i = 0; i <= count ; i++){
    cout << currentArray.cityNode[i].destCity <<endl;

    }
}

我将值输入到图形副本中,然后将其输出到currentArray !!

1 个答案:

答案 0 :(得分:1)

您似乎认为可以使用a < b合理地比较字符数组。事实并非如此。您需要先查看strcmp(),或者首先使用std::string。就个人而言,我还强烈建议将合并排序算法完全独立于任何特定结构,并确保我可以合理地交换我的节点。