首页 > 解决方案 > 二维字符串数组冒泡排序

问题描述

我想弄清楚如何对二维字符串数组进行冒泡排序。我目前正试图弄清楚为什么我的程序没有对字符串进行排序。我怀疑 void swap 可能有问题。我觉得需要将二维数组放入其中。我不太确定我刚刚学会了如何创建冒泡排序算法。

#包括

using namespace std;

  const int SIZE = 2;
  const int ROWS = 2;

void bubbleSort(string values[][SIZE]);
void swap(int &, int &);

int main ()

{



    string values[ROWS][SIZE] = {{"A23", "A12"}, {"name1", "name2"}};

    cout << "Unsorted Values: " << endl;


    for(auto element : values)
        cout << element << " ";

    cout << endl;

    cout << "Sorted Values" << endl;

         bubbleSort(values);
            for (auto element:values)

        cout << element << " ";

    return 0;

}

void bubbleSort(string values[][SIZE])
{
    int maxElement;
    int index;

    for (maxElement = SIZE - 1; maxElement > 0; maxElement--)
    {
        for( index = 0; index < maxElement; index++)
        {
            if (values[0][index] > values[0][index + 1])
            {
                swap(values[0][index], values[0][index + 1]);
            }
        }
    }
}

void swap(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

标签: c++

解决方案


您的程序会打印出地址,因为您的打印循环会迭代字符串二维数组的每个条目。因此,每个条目都是一个数组。所以arr保存指向数组第一个元素的指针。您只需要一个嵌套循环来打印出单个元素的值:

for (auto row : values)
    for (int i = 0; i < SIZE; i++)
        std::cout << row[i] << " ";

此外,不需要实现自己的交换功能。只需使用std::swap(T&,T&)

但我假设您想要实现多数组排序。然后你应该使用一个简单的结构来表示一个实体而不是多个数组,并实现一个运算符来比较两个实体。我建议也使用基于范围的容器。然后,您可以利用标准的排序功能。

#include <string>
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

struct Entry
{
    string id;
    string name;

    bool operator<(const Entry& comp)
    {
        return id < comp.id;
    }
};

int main()
{
    auto print = [](const vector<Entry>& vec)
    {
        for (auto& el : vec)
        {
            cout << el.id << "->" << el.name << "\t";
        }   
    };


    vector<Entry> values { {"A23","name1" }, {"A12", "name2"} };

    cout << "Unsorted Values: " << endl;
    print(values);
    cout << endl;

    std::sort(values.begin(), values.end());
    cout << "Sorted Values" << endl;
    print(values);


    return 0;
}

打印出来:

Unsorted Values:
A23->name1   A12->name2
Sorted Values:
A12->name2   A23->name1

推荐阅读