user3100177
user3100177

Reputation: 61

Sorting through Pointers

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

Answers (2)

Pandrei
Pandrei

Reputation: 4951

I assume you are sorting the array in ascending order; when doing that, you are doing several things wrong:

  1. you are aways swaping *ptr and *(ptr+1) -> you need to add z to this equation or the pointer will never increment.
  2. after the first iteration you have the largest element in the array on the last position, so now you need to stop just before the last position with the comparisions

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

Glandy
Glandy

Reputation: 91

reset your Pointer ptr after your loop with "z" Set it back to ptr = arr;

Upvotes: 3

Related Questions