I need to sort a 2d array. My idea is to turn the matrix into 1d array, then sort and convert the resulting array back into a matrix.
But while working, I encountered a problem. Here are the screenshots of output at the moment.
The first row is a transformed matrix filled with random numbers. And the second - the result of sorting. At first I thought that only part is sorted, but there is a certain pattern. It just first writes the numbers from 0 to 10 that occur in the array; and then displays the remaining numbers. And I dont understand why depends on how to make it sort properly. I also send the code
#include <iostream>
#include <iomanip>
#include<bits/stdc++.h>
using namespace std;
// Tree Sort
struct Node
{
int key;
struct Node *left, *right;
};
// Допоміжна функція для створення нового вузла
struct Node *newNode(int item)
{
struct Node *temp = new Node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// Stores inorder traversal of the BST
// in arr[]
void storeSorted(Node *root, int arr[], int &i)
{
if (root != NULL)
{
storeSorted(root->left, arr, i);
arr[i++] = root->key;
storeSorted(root->right, arr, i);
}
}
/*Допоміжна функція для вставки нового
вузла із заданим ключем */
Node* insert(Node* node, int key)
{
/* Якщо дерево порожнє до нового вузла */
if (node == NULL) return newNode(key);
/* В іншому випадку вниз по дереву */
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
/* повернути (без змін) покажчик вузла */
return node;
}
// функция сортировки arr[0..n-1] Tree Sort
void treeSort(int arr[], int n)
{
struct Node *root = NULL;
// Construct the BST
root = insert(root, arr[0]);
for (int i=1; i<n; i++)
root = insert(root, arr[i]);
// Store inorder traversal of the BST
// in arr[]
int i = 0;
storeSorted(root, arr, i);
}
//перетворення матриці в одновимірний масив
int main() {
//матриця
int n=2, m=12;
srand(time(NULL)); // генератор випадкових чисел.
int a[n][m];
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = rand()%11 ;
}
}
}
// переобразование
int arr[n*m];
// одновимірний масив
memcpy(arr,a,24*sizeof(int));
for (int i=0; i<n*m; i++) {
cout<<arr[i]<<" ";
}
cout<<endl;
treeSort( arr, n*m);
for (int i=0; i<n*m; i++) {
cout<<arr[i]<<" ";
}
return 0;
}