按第一个数字的降序对文件中的数字进行冒泡排序

Bubble sort the numbers from a file in descending order for the first number

我想使用二维数组的“冒泡排序”算法进行排序。我的数组大小约为 array[100000][100000]。我输入的数字是 n=100,000.

For now we can use a small size of the array to fix the sorting issue.

  1. 我需要按第一个数字(第一个数字的行)的降序对它们进行排序。
  2. 如果两个值的第一个数相同,那么我必须根据第二个数对它们进行排序。
  3. 最后我要把结果输出到一个txt文件中

让我们用一个例子来理解。在这里,我的输入看起来像这样

41 11
34 4
69 4
78 6
62 8
5 5
81 3
5 10

在我们的输入示例上方,我们有几个输入。现在我需要对第一个数字进行降序排序。但是如果2个值的第一个数相同,则按照第二个数排序。

下面的示例输出,

81 3
78 6
69 4
62 8
41 4
34 4
5 10
5 5

如果有人可以帮助我。

我是初学者,所以我尝试手动输入文件来解决这个排序问题。我可以解决排序问题然后我会尝试输入和输出文本。

我尝试过但没有奏效的东西。我还在努力解决。

#include<bits/stdc++.h>
#include <algorithm>
using namespace std;

int main ()
{
    int arr[100][100];
    int n,j;
    cin >>n;
    cout << "Please enter a number: " << endl;
    for(int i=0;i<n;i++)
    {   for (int j=i; j<n; j++)
        {
            cin>>arr[i][j];
        }
    }
    cout << "Unsorted array:" << endl;
    for (int i=0; i<n; i++)
    {
        for (int j=i; j<n; j++)
        {
             cout<<arr[i][j]<<"\t";
        }

    }

    for (int i=0; i<=n; i++)
    {
        for (int j=i+1; j<=n-1; j++)
        {
            int temp;
            if(arr[i]>arr[j])
            {
                temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }
    }
return 0;
}

为您的基础容器使用 std::vector<std::array<int,2>>std::vector 的动态增长能力解决了你的堆栈 space 问题,而 std::array 的使用为你提供了绑定单元格比较。 IE。你可以这样做:

std::array<int, 2> ar1{1,2}, ar2{1,3};

if (ar1 < ar2) ...

它会做正确的事。然后结果有效地归结为:

#include <iostream>
#include <array>
#include <vector>
#include <utility>

int main()
{
    std::vector< std::array<int,2> > v;
    std::size_t n;
    if (std::cin >> n && n > 0)
    {
        std::array<int,2> row;
        while (n-- && std::cin >> row[0] && std::cin >> row[1])
            v.emplace_back(row);

        // bubblesort the content
        std::size_t len = v.size();
        while (len-- > 0)
        {
            bool swapped = false;
            for (std::size_t i=0; i<len; ++i)
            {
                // std::array support multi-cell comparison.
                if (v[i] < v[i+1])
                {
                    // use library swap to swap entire row.
                    std::swap(v[i], v[i+1]);
                    swapped = true;
                }
            }

            // early exit if no swaps happened on the last pass
            if (!swapped)
                break;
        }

        // report final output.
        for (auto const& row : v)
            std::cout << row[0] << ' ' << row[1] << '\n';
    }
}

输入

8
41 11
34 4
69 4
78 6
62 8
5 5
81 3
5 10

输出

81 3
78 6
69 4
62 8
41 11
34 4
5 10
5 5