Reputation: 61
Please tell my errors I am using bubble sort method to sort an array, i want it using pointer plz correct my mistakes, i m new to c++. I think my mistake is in sorting condition.
#include <iostream>
using namespace std;
int main() {
//sorting
int arr[5];
int *ptr;
ptr = arr;
int temp;
for (int i = 0; i < 5; i++) {
cin >> *(ptr+i);
}
for (int i = 0; i<5;i++) {
for (int z = 0; z<4; z++) {
if (*(ptr+1) < *ptr) {
temp = *ptr;
*ptr = *(ptr+1);
*(ptr+1) = temp;
}
*(ptr++);
}
}
for (int i = 0; i < 5; i++) {
cout << *(ptr+i) << endl;
}
return 0;
}
Upvotes: 0
Views: 124
Reputation: 4951
I assume you are sorting the array in ascending order; when doing that, you are doing several things wrong:
The code should look like thins:
for (int i = 0; i<5;i++) {
for (int z = 0; z<4-i; z++) {
if (*(ptr+z+1) < *(ptr+z)) {
temp = *(ptr+z);
*(ptr+z) = *(ptr+z+1);
*(ptr+z+1) = temp;
}
}
}
Upvotes: 1
Reputation: 91
reset your Pointer ptr after your loop with "z" Set it back to ptr = arr;
Upvotes: 3