c++arrayspointersbubble-sort

Sorting an Array of Pointers in C++


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.


Solution

  • SwapIntPtr swaps the values, not the pointers. Just use std::swap or if you really need to implement your own swap:

    static void SwapIntPtr(int*& a, int*& b)
    {
      int* temp = a;
      a = b;
      b = temp;
    }
    

    Note that the pointers need to be passed by reference in order for the swap function to be able to modify them.

    It would be simpler to use std::sort:

    std::sort(ptrarr, ptrarr + size, [](int* a, int* b) { return *a < *b; });