'bubble sort with pointer in C ,expected declaration or statement at end of input
I try to implement bubble sort with references the array elements with pointers, rather than using array indexing.
void bubble_p(long *, long);
int main(){
long count = 10;
int i;
long data[]= {5,2,1,7,10,6,8,4,9,0};
bubble_p(data, sizeof(data)/sizeof(long));
for(i=0;i<sizeof(data)/sizeof(data[0]);i++){
printf("%ld\n",data[i]);
}
return 0;
}
void bubble_p(long *data, long count) {
long *last = data + count - 1;
while (data < last) {
long *i = data;
while (i < last) {
long cur = *i;
long next = *(i + 1);
if (next < cur) {
*i = next;
*(i + 1) = cur;
}
i++;
}
last--;
}
}
Edited: Now the code works perfectly
Any help would be appreciated.
Solution 1:[1]
Why are you passing count of 10 when the array only has 5 elements?
As declared, it will allocate 5 elements and throw away the rest of your initializer data.
Instead, you should do something like this:
long data[]= {5,2,1,7,10,6,8,4,9,0};
bubble_p(data, sizeof(data)/sizeof(long));
Let the compiler figure out how big to make the array, and rather than hardcoding the size, let the compiler figure that out too.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user10489 |
