Bubble sort using only pointers and dynamic memory

2019-09-20 19:23发布

问题:

I am trying to run Bubble Sort Technique using pointers and dynamic memory allocation, but the code doesn't seem to run (eclipse crashes). Please help. I am posting the code below:

#include<iostream>
using namespace std;

void sort(int *);

//===========================================
int main()
{
    int *a = new int[5];
    int *c = a;

    cout << "Enter the numbers\n";
    for(int i = 0; i < 5; i++)
    {
        cin >> *a;
        a++;
    }

    a = a - 4;

    sort(a);

    cout << c;
    cout<<"\nSorting complete";
    cout<<"\n Array after sorting";

    for(int i = 0; i < 5; i++)
    {
        cout << *c << endl;
        c++;
    }

    delete []a;
    delete []c;

    a = c = NULL;

    return 0;
}
//===========================================
void sort(int *a)
{
    int *b = a + 1;

    for(int i = 0; i < 5; i++)
    {
        if(*a > *b)
        {
            int temp = *a;
            *a = *b;
            *b = temp;
             a++;
             b++;
        }
        else  
        { 
            b++;
            continue;
        }
    }
}

Thank you in advance.

回答1:

Here:

int *a=new int[5];
int *c=a;
cout<<"Enter the numbers\n";
for(int i=0;i<5;i++)
{
  cin>>*a;
  a++;
}

a=a-4;

You increase a by 5, then reduce it by 4. You then try to sort starting from the 1 position but assuming 5 elements, so you march past the end of the array. If you correct this (e.g. a=c;), you will perform one pass of the bubble sort correctly (I think). You must perform more than one pass to sort the array fully.

EDIT: P.S. you are also trying to delete the array twice, which is unnecessary (and undefined behavior).



回答2:

Make life easy

Get rid of code like

cin>>*a;
a++;

And use

cin>>a[i];

Use the same idea elsewhere