首页 文章

按字母顺序排序c字符串数组

提问于
浏览
0

我有一个功课问题我有点问题,我被要求使用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;
}

1 回答

  • 1

    更改

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

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

    更新:而不是stricmp,你可以使用strcasecmp

相关问题