2013-11-07 3 views
0

Это мой код. Я не знаю, как получить код для запуска. У меня возникают проблемы с quicksorting для строки.quicksort string array help C++

#include <iostream> 
#include <fstream> 
#include <cstdlib> 
#include <time.h> 
#include <string> 
#include <ctime> 
#include <stdio.h> 



using namespace std; 

int count; 
template <class T> 
void printArray(T ar[], int sz); 
template <class T> 
void bubbleSort(T ar[], int sz); 
void quickSortMain(string items[], int ct); 
void quickSort(string items[], int left, int right); 

////////////////////////////////////////////////////////////////////////// 
// Main Function Implementation 
////////////////////////////////////////////////////////////////////////// 

int main() { 
    int numOfData = 50000; 
    string line, temp; 
    ofstream resultFile; 
    ofstream tableFile; 
    double data[100][2]; 
    string patient[numOfData]; 
    ifstream dataFile("shufflePatient.txt"); 
    int i; 
    int SIZE = 0; 

    cout << "Program to shuffle data" << endl << endl; 
    cout << "This program will calculate swapping processes and running time."; 


    /*Storing data*/ 
    cout << "Reading data in process.." << endl; 
    if (dataFile.is_open()) { 
     i=-1; 
     while (dataFile.good()) { 
      getline (dataFile, line); 
      if (i>=0) patient[i] = line; 
      i++; 
     } 
     dataFile.close(); 
    } 

    SIZE = 5; 
    quickSortMain(patient, 5); 


    /*Writing to file*/ 
    cout << "Writing to file.." << endl; 
    resultFile.open ("test.txt"); 
    for (int i=0 ; i<numOfData ; i++) { 
     resultFile << patient[i] << "\n"; 
    } 
    resultFile.close(); 
    system("pause"); 
    return 0; 
} 


void quickSortMain(string items[], int ct) 
{ 
    quickSort(items, 0, ct-1); 
} 


void quickSort(string items[], int left, int right) 
{ 
    int i, j; 
    char *x; 
    string temp[10]; 

    i = left; 
    j = right; 
    x = items[(left+right)/2]; 

    do { 
    while((strcmp(items[i],x) < 0) && (i < right)) { 
     i++; 
    } 
    while((strcmp(items[j],x) > 0) && (j > left)) { 
     j--; 
    } 
    if(i <= j) { 
     strcpy(temp, items[i]); 
     strcpy(items[i], items[j]); 
     strcpy(items[j], temp); 
     i++; 
     j--; 
    } 
    } while(i <= j); 

    if(left < j) { 
    quickSort(items, left, j); 
    } 
    if(i < right) { 
    quickSort(items, i, right); 
    } 
} 









//---------------------------------------------------------------------------- 
// prints array of size size 
//---------------------------------------------------------------------------- 
template <class T> 
void printArray(T patient[], int size) 
{ 
    for(int i = 0; i < size; i++) 
    cout << patient[i] << " "; 
    cout << endl; 
} 




//---------------------------------------------------------------------------- 
// sorts array of size size by Bubble Sort method 
//---------------------------------------------------------------------------- 
template <class T> 
void bubbleSort(T patient[], int size) //returning an int 
{ 
    bool noChange = true; 
    for(int i = size; i > 0; i--) 
    { 
    noChange = true; 
    for(int j = 1; j < i; j++) 
    { 
     if(patient[j] < patient[j - 1]) 
     { 
     swap(patient[j], patient[j-1]); 
     count = count + 1; 
     noChange = false; 
     } 
    } 
    if (noChange) 
     return ; 
    } 
} 

ошибка я получил, был в этой линии:

x = items[(left+right)/2]; 

Я изменил

char x*; в string x;

Я не знаю, если это было правильно. Теперь ошибка im get заключается в том, что strcmp и strcpy не объявлены. Любая помощь в том, что я должен делать дальше?

+0

VLAs не являются стандартными. – chris

+0

Строки можно сравнить с '<' and '>' и присваиваться '='. Нет необходимости в 'strcmp' и' strcpy'. –

+0

1. Избавьтесь от 'left' и' right', вам нужно только len, если вы дистанционно владеете математикой указателя. 2. Прекратите использовать функции выполнения C для вещей, предоставленных для вашей среды выполнения C++, например 'operator <' overload для 'std :: string' – WhozCraig

ответ

2

Это правильно, теперь изменить

strcmp(items[i],x) < 0 

в

items[i] < x 

и

strcmp(items[j],x) > 0 

в

items[j] > x 

и

strcpy(temp, items[i]); 

в

temp = items[i]; 

т.д.

Но на самом деле это случай RTFM. Если вы достаточно компетентны, чтобы написать процедуру быстрой сортировки, вы должны быть достаточно компетентны, чтобы посмотреть, как работает std::string. Возможность доступа к справочной информации - очень важный навык для программиста.

+0

Также измените' string temp [10]; 'на' string temp; 'хотя 'std :: swap' будет лучшим выбором для обмена предметами. –

+0

@RetiredNinja Право, я пропустил это. Я предполагаю, что это был 'char temp [10];'. 'std :: swap' - лучший выбор, но я оставил его, чтобы показать эквивалентность' strcpy' и '='. Возможно, OP может практиковать свои исследовательские навыки, просматривая 'std :: swap'. – john

+0

благодарим вас за комментарии! последний вопрос. Можете ли вы, ребята, посоветовать нам, где я должен исследовать std :: string и std :: swap? большинство веб-сайтов, которые я открываю, действительно не очень хорошо объясняют обоим из них в отношении быстрой сортировки. – user2959974