- #1
loonychune
- 92
- 0
I have been asked to code a Bubble Sort using a pointer array and pointer notation as opposed to the square bracket notation...(there should be two uses of square brackets when declaring the arrays). It will not work! :(
Basically the data does not sort. I am trying to swap pointer array elements rather than the main array elements (as this is a faster process) but cannot quite figure it out.
A quick gander over the work would be much appreciated!
#include <iostream>
using namespace std;
const int size = 1000;
int main(void){
int arr[size];
int *p[size];
for(int i = 0; i < size; ++i){
*(p + i) = (arr + i);
} //each pointer *p gives the address of arr
int j = sizeof(arr)/sizeof(int);
for(int i = 0; i < size; ++i){
cout << "Please enter an integer (0 to end):" << ' ';
cin >> *(arr + i);
if (*(arr + i) == 0){
j = i - 1;
break;
}
}
cout << "\nThe unsorted array is:\n" << endl;
for(int i = 0; i < j + 1; ++i){
cout << "Element "<< i <<": " << *(arr + i) << endl;
}
int *t;
for(int a = 0; a < j; ++a){ //determines number of passes
for(int i = 0; i < j; ++i){ //iterates through input data for each pass
if(*(arr + i) > *(arr + i + 1)){
t = *(p + i);
*(p + i) = *(p + i + 1);
*(p + i + 1) = t;
}
}
} //end of bubble sort
cout << "\nThe sorted array is:\n" << endl;
for(int i = 0; i < j + 1; ++i){
cout << "Element "<< i <<": " << *(arr+i) << endl;
}
cout << "\nThank you for using Bubble Sort." << endl;
} // end of main
Basically the data does not sort. I am trying to swap pointer array elements rather than the main array elements (as this is a faster process) but cannot quite figure it out.
A quick gander over the work would be much appreciated!
#include <iostream>
using namespace std;
const int size = 1000;
int main(void){
int arr[size];
int *p[size];
for(int i = 0; i < size; ++i){
*(p + i) = (arr + i);
} //each pointer *p gives the address of arr
int j = sizeof(arr)/sizeof(int);
for(int i = 0; i < size; ++i){
cout << "Please enter an integer (0 to end):" << ' ';
cin >> *(arr + i);
if (*(arr + i) == 0){
j = i - 1;
break;
}
}
cout << "\nThe unsorted array is:\n" << endl;
for(int i = 0; i < j + 1; ++i){
cout << "Element "<< i <<": " << *(arr + i) << endl;
}
int *t;
for(int a = 0; a < j; ++a){ //determines number of passes
for(int i = 0; i < j; ++i){ //iterates through input data for each pass
if(*(arr + i) > *(arr + i + 1)){
t = *(p + i);
*(p + i) = *(p + i + 1);
*(p + i + 1) = t;
}
}
} //end of bubble sort
cout << "\nThe sorted array is:\n" << endl;
for(int i = 0; i < j + 1; ++i){
cout << "Element "<< i <<": " << *(arr+i) << endl;
}
cout << "\nThank you for using Bubble Sort." << endl;
} // end of main