Home > Blockchain >  Bubble sorting using pointers but I have to use pointers to traverse as well
Bubble sorting using pointers but I have to use pointers to traverse as well

Time:01-27

I have to create a bubble sort program using pointers but instead of using i and j for iterations, I have to use pointers.

#include<iostream>

using namespace std;

int main() {

int size = 6;
int size1 = size;
int arr[] = { 8, 6, 11, 3, 15, 5 };
int* myarr = arr;


int* endptr = myarr   size;
int* endptr2 = myarr   size;



for (myarr; myarr < endptr; myarr  ) {
    for (myarr; myarr < endptr2; myarr  ){
        if (*myarr > *(myarr   1)) {
            swap(*myarr, *(myarr   1));
        }

    }
    endptr2--;
    
    
}

}

The first loop is working good but I am not able to iterate the second loop for bubble sort.

CodePudding user response:

Something like this?

#include <iostream>
#include <vector>

void bubblesort( int arr[], int N ) {
    if ( N<2 ) return;
    for ( int* endptr = &arr[N-1]; endptr>arr; --endptr ) {
        for ( int* p = arr; p<endptr;   p ) {
            if ( p[0] > p[1] ) {
                std::swap(p[0],p[1]);
            }
        }
    }
}

int main() {
    std::vector<int> values = {10,3,8,1,2,3,7,9};
    bubblesort( values.data(), values.size() );
    for ( int value : values )  {
        std::cout << value << " ";
    }
    std::cout << std::endl;
}

Produces

1 2 3 3 7 8 9 10 

https://godbolt.org/z/56roK56do

  • Related