Bubble sort using only pointers and dynamic memory allocation

最后都变了- 提交于 2019-12-13 07:48:34

问题


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



来源:https://stackoverflow.com/questions/34711643/bubble-sort-using-only-pointers-and-dynamic-memory-allocation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!