Reputation: 23
Ive been trying to get the code to sort an user inputted array using a pointer based bubble sort in C++. The code compiles without error, but the array doesn't get sorted. Pointers have never been my strong area and I cant get them to work correctly. Heres my code.
#include <iostream>
using namespace std;
int main()
{
int arr[10];
int i = 0;
for (i = 0; i < 10; i++)
{
cout << "Enter a number: ";
cin >> arr[i];
}
int *ptr = &i;
for (int j = 0; j < 9; j++)
{
if (*(ptr + j) > *(ptr + j + 1))
{
int temp = *(ptr + j);
*(ptr + j) = *(ptr + j + 1);
*(ptr + j + 1) = temp;
}
}
cout << endl;
for (i = 0; i < 10; i++)
cout << arr[i] << "\t";
cin.ignore();
cin.get();
}
Thanks for the help guys.
Upvotes: 2
Views: 8713
Reputation: 56557
You have 3 mistakes:
int* ptr
should point to the array arr
, int* ptr = arr;
j = 8
)You need to keep sorting until there are no more swaps:
bool sorted = false; // keep track here whether you still need to sort
int *ptr = arr;
while (!sorted) // repeat this until no more swaps
{
sorted = true;
for (int j = 0; j < 8 ; j++) // Repeat until N - 1 (i.e. 8 in this case)
{
if (*(ptr + j ) > *(ptr + j + 1)) // make sure you don't access out of bounds
{
int temp = *(ptr + j);
*(ptr + j) = *(ptr + j + 1);
*(ptr + j + 1) = temp;
sorted = false; // we swapped, so keep sorting
}
}
}
Upvotes: 2