2D 字符串数组气泡排序
2D String Array Bubble Sort
我正在尝试弄清楚如何对 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
相关文章:
- 在气泡排序程序中未声明错误功能
- 气泡排序未正确循环
- 带有枚举方向/类型的气泡排序结构数组
- 在气泡排序中使用递归
- 如何在C++中实现气泡排序?
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- C++气泡排序的问题
- 气泡排序C++ OOP
- OOP 气泡排序C++程序
- 按升序对列表进行排序,C++使用气泡排序
- C++气泡排序
- 此气泡排序代码中的错误是什么?
- 气泡排序 2D 数组
- 如何使用气泡排序从最小到最大对 4 个数组进行排序? C++
- 添加气泡排序代码以排列列表
- 使用向量和气泡排序的动态内存分配
- 带修改(偏移)的气泡排序
- 使用C++进行气泡排序
- 气泡阵列在C 实现中排序
- 选择排序与气泡排序C++