按一列对二维数组进行气泡排序
Bubble sort on a two dimensional array by one column
我必须按列对矩阵进行排序;作为输入,我有一个一维数组,O将其转换为矩阵:
int arr[] = { 6, 7, 3, 1, 3, 2, 4, 4, 7, 5, 1, 1, 5, 6, 6, 4, 5 };
列中的第一个元素是值,第二个元素是外观的数量。我必须按值(按第一列)对它们进行排序。这就是我到目前为止尝试过的。
直方图.h
#ifndef HISTOGRAM_H
#define HISTOGRAM_H
#include<iostream>
class Histogram
{
private:
int** matrix;
int lines;
void SortMatrix();
public:
Histogram(){ }
Histogram(int elements[], int elementsNr);
Histogram(int** m, int l);
void Print();
};
#endif
直方图.cpp
#include"histogram.h"
using namespace std;
Histogram::Histogram(int** m, int l)
{
matrix=m;
lines=l;
SortMatrix();
}
Histogram::Histogram(int elements[], int elementsNr)
{
lines=0;
//initialize matrix : elementrNr lines and 2 columns
matrix=new int*[elementsNr];
for(int i=0;i<elementsNr;i++)
{
matrix[i]=new int[2];
matrix[i][0]=INT_MIN;
matrix[i][1]=INT_MIN;
}
//search each element from the array in the matrix
bool found=false;
for(int i=0;i<elementsNr;i++)
{
found=false;
for(int j=0;j<elementsNr;j++)
{
//the element was found in the matrix ( on the first column )
if(matrix[j][0] == elements[i])
{
matrix[j][1]++;
found=true;
break;
}
}
if(!found)
{
matrix[lines][0]=elements[i];
matrix[lines][1]=1;
lines++;
}
}
SortMatrix();
}
void Histogram::SortMatrix()
{
bool flag=true;
int temp1;
int temp2;
int i=0;
for(int i=0;(i<lines-1) && flag;i++)
{
flag=false;
if(matrix[i][0]>matrix[i+1][0])
{
temp1=matrix[i][0];temp2=matrix[i][1];
matrix[i][0]=matrix[i+1][0];
matrix[i][1]=matrix[i+1][1];
matrix[i+1][0]=temp1;matrix[i+1][1]=temp2;
flag=true;
}
}
}
void Histogram::Print()
{
for(int i=0;i<lines;i++)
{
cout<<matrix[i][0]<<" : " <<matrix[i][1]<<endl;
}
}
但此代码的输出是:
6:3
7:2
3:2
1:3
2:1
4:3
5:3
相反:
1:3
2:1
3:2
4:3
5:3
6:3
7:2
试试这个:
for (int i = 0; (i < lines - 1); i++) {
for (int o = 0; (o < lines - 1); o++) {
if ( matrix[ i ][0] < matrix[ o ][0] ) {
temp1 = matrix[ i ][0];
temp2 = matrix[ i ][1];
matrix[ i ][0] = matrix[ o ][0];
matrix[ i ][1] = matrix[ o ][1];
matrix[ o ][0] = temp1;
matrix[ o ][1] = temp2;
}
}
}
您需要两个循环才能排序。我相信您没有正确实现这一点,因为下面的演示表明它可以工作。
Ideone 演示
相关文章:
- 将值从二维数组输出到文本文件
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- 如何正确填充在堆上分配的二维数组?
- 传递二维数组时出现问题
- 具有随机数的二维数组不会更改
- 如何在C++中获取二维数组中最少的一列数?
- 如何使用用户输入变量制作二维数组?
- C++ 中动态二维数组的访问冲突
- 遍历二维数组的所有子数组
- 将二维数组的所有元素插入到一维数组中
- 在函数中传递二维数组
- 为什么指针在对二维数组进行排序时无法正常工作?
- 创建 std::string 的二维数组的最佳做法
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 元素在二维数组 c++ 中的出现次数
- 执行 c++ 二维数组
- C++ 中的二维数组初始化为一个值
- 在C++中初始化第一维大小未知的二维数组
- 按一列对二维数组进行气泡排序