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;
        }
    }
4
  • How did you create the A matrix? If the data is in contiguous memory like this answer, 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. Commented Jul 22, 2020 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. Commented Jul 23, 2020 at 0: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. Commented Jul 23, 2020 at 0:31
  • See this example, and see this answer for an explanation on the index array to aid in the sorting. Commented Jul 23, 2020 at 0:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.