2D 字符串数组气泡排序

2D String Array Bubble Sort

本文关键字:排序 气泡 数组 字符串 2D      更新时间:2023-10-16

我正在尝试弄清楚如何对 2D 字符串数组进行气泡排序。我目前试图弄清楚为什么我的程序没有对字符串进行排序。我认为无效交换可能有问题。我觉得需要把 2D 阵列放在那里。我不太确定我刚刚学会了如何创建气泡排序算法。

#include

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;
}

程序会打印出地址,因为打印循环会迭代字符串 2D 数组的每个条目。因此,每个条目都是一个数组。因此,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