I'm trying to sort an array of pointers according to the values in an array, leaving the original dataset alone. However, when I output the pointer array and then the data array, they both have the same sorted values. How can I sort the array of pointers without changing data[]?
I think what's happening is that the values that arrptr[] is pointing to are being sorted and in turn the data[] array is somehow being messed up. I tried using a pointer to a pointer but only got errors (int** to int* conversion).
For reference, this is how I assigned the pointer array to the data array:
for (int i = 0; i < size; i++)
{
ReadingFile >> num1;
data[i] = num1;
ptrarr[i] = &data[i];
}
These are the display functions that output the same exact sorted result:
static void DisplayArray(int* ptrarr[], int size)
{
cout << "The Pointer Array of sorted pointer elements:\n";
for (int i = 0; i < size; i++)
{
cout << *ptrarr[i] << " "; //gives same result as DisplayData
}
cout << endl;
return;
}
static void DisplayData(int data[], int size)
{
cout << "Data Array elements are:\n";
for (int i = 0; i < size; i++)
{
cout << data[i] << " ";
}
cout << endl;
return;
}
Here are my sorting functions:
static void SwapIntPtr(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
return;
}
static void Sorting(int* ptrarr[], int size)
{
for (int i = 0; i < size - 1; i++)
{
for (int j = 0; j < size - i - 1; j++)
{
if (*ptrarr[j] > *ptrarr[j + 1])
{
SwapIntPtr(ptrarr[j], ptrarr[j + 1]);
}
}
}
return;
}
It's hard for me to see the issue as everything looks like it should work. However, I'm hoping a fresh set of eyes could help me see the problem.
int ** aandint ** b.ints, right? And it's swapping theints, right? Well, if your goal is to sort the pointers, which involves swapping the pointers, then swapping theints, instead would be described by Mr. Spock as "highly illogical".std::sortwith a suitable lambda for the comprison function.int temp = *a;shows that you are sorting integers, not pointers.int*? Sorting ints directly would have been more easy, there is no need for pointers here. Then you use "C" style arrays, wherestd::span(C++20) is probably the better choice, adn finally as said just use std::sort. If someone is teaching you C++ it looks like that someone is teaching you a somewhat dated version of C++. Note for arrays it is more idiomatic to usestd::vector<int>.