Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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() {

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading