按一列对二维数组进行气泡排序

Bubble sort on a two dimensional array by one column

本文关键字:二维数组 气泡 排序 一列      更新时间:2023-10-16

我必须按列对矩阵进行排序;作为输入,我有一个一维数组,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 演示