0

I'm trying to sort the matrix A in ascending order. After the determination of the next minimum element, I delete the corresponding indices with flag[jj]=false. But after k loop, I want to remake all of them true. How can I do it?

double min;
int jj = 0;
double** A;
double** B;


bool* flag;
flag = new bool[n];

for (int i = 0; i < n; i++)
{
    flag[i] = true;
}


for (int i = 0; i < n; i++)
{
        for (int k = 0; k < n; k++)
        {
            min = 10000;
            for (int j = 0; j < n; j++)
            {
                if (flag[j] == true)
                {
                    if (A[i][j] < min)
                    {
                        min = A[i][j];
                        jj = j;
                    }
                }
            }
            flag[jj] = false;
            B[i][k] = min;
        }
    }
Panwen Wang
  • 3,573
  • 1
  • 18
  • 39
ecp20
  • 1
  • How did you create the `A` matrix? If the data is in contiguous memory like [this answer](https://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048), then a simple call to `std::sort` is all you need, and not have to mess around with `flag` variables and loops. At the link, it even has an example of sorting a 2D matrix using `std::sort`. – PaulMcKenzie Jul 22 '20 at 23:51
  • Thank you for your answer. I want to keep the indices of these elements respectively in another matrix as well, that's why I preferred this way. – ecp20 Jul 23 '20 at 00:20
  • If you want to sort the matrix without moving the elements, it can still be done using a single flag matrix and call to `std::sort`. – PaulMcKenzie Jul 23 '20 at 00:31
  • [See this example](http://coliru.stacked-crooked.com/a/d68c1e502ec315fe), and see [this answer](https://stackoverflow.com/questions/46382252/sort-array-by-first-item-in-subarray-c/46382976#46382976) for an explanation on the index array to aid in the sorting. – PaulMcKenzie Jul 23 '20 at 00:59

1 Answers1

0

The most straightforward way would be to use what you already have. Similar to how you are already setting the flags to true at the beginning, you could copy that loop after your for(k) loop and this would set them all to true.

Durstann
  • 122
  • 11
  • Or better, you could replace the manual loops with the standard `std::fill/_n()` algorithm instead, eg `std::fill(flag, flag+n, true);` or `std::fill_n(flag, n, true);` – Remy Lebeau Jul 23 '20 at 00:03