zen zen - 3 months ago 13
C Question

making program of bubble sort using pointer

I had created bubble sort program but on running these program I am getting error, I want to implement it using pointer and I am returning array of element using pointer, I am pasting my code here:

/// bubble sort
#include <stdio.h>

int *bble(int a[], int tot) {
int i, j;
int temp;
for (i = 0; i < tot; i++) {
for (j = 0; j < tot - i - 2; j++) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
return a;
}

int main() {
int tot = 10, k;
int a[tot];
int *p;
int i;

for (i = 0; i < 10; i++) {
a[i] = (i * 10);
}

a = bble(a, tot);
for (k = 0; k < tot; k++) {
printf("element is %d", *(p + i));
printf("\n");
}
return 0;
}


And problem which I am getting is:

bubble.c: In function ‘main’:
bubble.c:33:2: error: assignment to expression with array type
a=bble(a,tot);
^

Answer

It is totally tested and refracted code it is working properly on my system and hope for same on your system and output of these code is also i am pasting ,

#include<stdio.h>

int *bble(int a[],int tot)
{
int i,j;
int temp;
for(i=0;i<tot-2;i++)
{
for(j=0;j<tot-i-2;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}

}
return a;
}

int main()
{
int tot=10,k;
int a[tot];

int i;
for(i=9;i>=0;i--)
{
a[i]=(i*10);
}

int *p;
int temp,j;
p=bble(a,tot);
for(k=0;k<tot-1;k++)
{
printf("element is %d",*(p++));

printf("\n");
}
return 0;
}

For simplicity you can just make program in simple manner, like it is reducing your overhead and doing same thing as you want in same time complexity and space complexity also ,so i suggest you to prefer simple manner ,

///bubble sort without pointer
#include<stdio.h>

int main()
{
int tot=10,k;
int a[tot];
int *p;
int i,j,temp;
for(i=0;i<10;i++)
{
a[i]=(i*10);
}
for(i=0;i<tot;i++)
{
for(j=0;j<tot-i-2;j++)
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;

}
for(k=0;k<tot;k++)
{
printf("element is %d", a[k]);
printf("\n");
}
return 0;
}

Output of both the code is here ,

element is 0
element is 10
element is 20
element is 30
element is 40
element is 50
element is 60
element is 70
element is 80

I want from you please check it on your system i am sure it will definatly work .