'How to bubblesort a pointers in the array without changing order of the array
So say I have two arrays intdataArray[10] = {61 34 46 114 73 29 13 93} and int *pointerDataArray[10] which has the pointers of the dataArray in the same respective index. How would I be able to sort the array through pointers and get the sorted array but also while still being able to print the original array.
My bubble sort is working but it is also changing dataArray as well.
This is the wanted output(correct)
dataArray before sort: 61 34 46 114 73 29 13 93
pointerArray before sort: 61 34 46 114 73 29 13 93
dataArray after sort: 61 34 46 114 73 29 13 93
pointerArray after sort: 13 29 34 46 61 73 93 114
This is the output I am getting(wrong)
dataArray before sort: 61 34 46 114 73 29 13 93
pointerArray before sort: 61 34 46 114 73 29 13 93
dataArray after sort: 13 29 34 46 61 73 93 114
pointerArray after sort: 13 29 34 46 61 73 93 114
Here is my code
#include <iostream>
#include <fstream>
using namespace std;
int readFile(string filename, int dataArray[10], int *pointerDataArray[10]);
void pointerSort(int dataArray[],int *pointerDataArray[] , int length);
void swapIntPtr(int *p1, int *p2);
void displayDataArray(int dataArray[], int length);
void displayPointerArray(int *pointerDataArray[], int length);
int main() {
int dataArray[10] = {};
int *pointerDataArray[10];
int length = readFile("arrayData.txt", dataArray, pointerDataArray);
cout << "dataArray before sort: ";
displayDataArray(dataArray, length);
cout << "pointerArray before sort: ";
displayPointerArray(pointerDataArray, length);
cout << endl;
pointerSort(dataArray, pointerDataArray, length);
cout << "dataArray after sort: ";
displayDataArray(dataArray, length);
cout << "pointerArray after sort: ";
displayPointerArray(pointerDataArray, length);
}
int readFile(string filename, int dataArray[10], int *pointerDataArray[10]) {
ifstream inputFile(filename);
if (inputFile.is_open()) {
int length;
inputFile >> length;
for (int i = 0; i < length; i++) {
inputFile >> dataArray[i];
pointerDataArray[i] = &dataArray[i];
}
return length;
}
return -1;
}
void pointerSort(int dataArray[],int *pointerDataArray[] , int length){
int i, j;
for (i = 0; i < length-1; i++)
for (j = 0; j < length-i-1; j++)
if (dataArray[j] > dataArray[j+1]) {
swapIntPtr(&dataArray[j], &dataArray[j + 1]);
}
}
void swapIntPtr(int *pointer1, int *pointer2) {
int pSwap = *pointer1;
*pointer1 = *pointer2;
*pointer2 = pSwap;
}
void displayDataArray(int dataArray[], int length){
for (int i = 0; i < length; i++) {
cout << dataArray[i] << " ";
}
cout << endl;
}
void displayPointerArray(int *pointerDataArray[], int length){
for (int i = 0; i < length; i++) {
cout << *pointerDataArray[i] << " ";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
