2014-02-09 4 views
0

숙제 문제가 있습니다. C와 함께 알파벳순으로 C 문자열 배열을 정렬하라는 메시지가 나타납니다. 정렬 알고리즘은 버블 정렬이어야합니다. 지금까지 내가 해왔 던 (아래에서 복제 한) 배열을 정렬 할 수 있지만 첫 번째 알파벳 만 기반으로합니다. 같은 알파벳으로 문자열을 어떻게 더 정렬합니까?알파벳순으로 C 문자열 배열 정렬

<snipped>@arch:~/College/OOP/Lab/W3$ cat 2.cpp 

/* 
* Write a function which sorts an array of C strings in ascending order using bubble sort. The 
* number of strings in the array and the array must be passed as parameters to the function 
*/ 

#include <iostream> 
#include <cstring> 

using namespace std; 

void sort(char **sar, unsigned num, unsigned len) 
{ 
    char *temp = new char[len]; 

    if (temp == NULL) 
    { 
     cout << "\nOut-Of-Memory\n"; 
     return; 
    } 

    for (unsigned a = 0; a < num-1; a++) 
    { 
     for (unsigned b = 0; b < ((num-a)-1); b++) 
     { 
      if (sar[b][0] > sar[b+1][0]) 
      { 
       strcpy(temp, sar[b]); 
       strcpy(sar[b], sar[b+1]); 
       strcpy(sar[b+1], temp); 
      } 
     } 
    } 

    delete[] temp; 
} 

int main(int argc, char *argv[]) 
{ 
    char **sar; 
    unsigned num; 
    unsigned len; 

    cout << "Number of Strings: "; 
    cin >> num; 
    cout << "Length of Strings: "; 
    cin >> len; 

    cin.ignore(); // Flush buffer to fix a bug (getline after cin). 

    sar = (char **) new char*[num]; 
    if (sar == NULL) 
    { 
     cout << "\nOut-Of-Memory\n"; 
     return -1; 
    } 

    for (unsigned i = 0; i < num; i++) 
    { 
     sar[i] = (char *) new char[len]; 
     if (sar[i] == NULL) 
     { 
      // Let's pretend we 'know' memory management 
      // because obviously modern OSs are incapable 
      // of reclaiming heap from a quitting process.. 
      for (unsigned j = 0; j < i; j++) 
       delete[] sar[j]; 
      cout << "\nOut-Of-Memory\n"; 
      return -1; 
     } 
    } 

    for (unsigned x = 0; x < num; x++) 
     cin.getline(&sar[x][0], 512); 

    sort(sar, num, len); 

    cout << '\n'; 
    for (unsigned y = 0; y < num; y++) 
     cout << sar[y] << '\n'; 

    for (unsigned z = 0; z < num; z++) 
     delete[] sar[z]; 
    delete[] sar; 

    return 0; 
} 
+0

잘못된 사용을 사용할 수 있습니다. 당신은'delete []'을 사용해야합니다. – Brandon

+0

정확히 어디? valgrind does not는 그런 무엇이라도에 관해서 미소 짓는다. – sgupta

+0

정렬 기능도 있습니다. 마지막에는 temp에'delete'를 호출합니다. 그것은'delete []'이어야합니다. – Brandon

답변

1

변화

if (sar[b][0] > sar[b+1][0])

UPDATE

if (stricmp(sar[b], sar[b+1]) > 0)

에 : 대신 stricmp, 당신은 delete``의 strcasecmp

+0

[해당] (http://publib.boulder.ibm.com/infocenter/iadthelp/v7r0/index.jsp?topic=/com.ibm.etools.iseries.langref.doc/rzan5mst264.htm)의 표준이 아닙니다. , 그렇지? (또한 [여기] (http://msdn.microsoft.com/en-us/library/ms235365.aspx) 참조) –

+0

많이 고마워! 나는 함수에 대해 조금 살펴 보았고 트릭을 수행하는 g ++ 매뉴얼에 상응하는 strcasecmp를 발견했다. – sgupta

관련 문제