user3127589
user3127589

Reputation: 37

Sorting array with BubbleSort

l changed my code but still cant figure out why it wont sort array...bubble sort only moves all elements one place to the right in my program instead of sorting array...l tired bsort and ssort and both do same thing shift elements for 1 position

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void bsort(int n,int a[])   
{
int i,j,k;
for(i=0;i<n-1;i++)  
{       
for(j=0;j<n-1;j++)
{   
        if(a[j]>a[j+1]);
            {

                k=a[j+1];
                a[j+1]=a[j];
                a[j]=k;

            }               
}   

} }

int main()
 {
int i,j,k,m,n;

srand(time(0));

printf("Unesi broj clanova niza:"); 
scanf("%d",&n);

int a[n];   

printf("Niz za sortiranje je:\n");
for(int i=0;i<n;i++) //Generisanje niza
{
    a[i]=rand()%(81);   
}

for(int i=0;i<n;i++) 
{
    printf("%3d",a[i]); 
}

bsort(n,a); 




 printf("\n\nSortirani niz je:\n");     
 for(i=0;i<n;i++)
 {
    printf("%3d",a[i]);

}

}

Upvotes: 0

Views: 696

Answers (2)

Alp
Alp

Reputation: 2826

There are several problems with your bubble sort implementation.

First, this line:

if (a[j] > a[j + 1]); {

is incorrect. The semi-colon terminates the conditional. As a result, the following block executes on every iteration of the inner loop and you end up unconditionally swapping a[j] and a[j+1] for every value of j. This means you're performing a nonsensical rearrangement of the array.

Second, you're not dealing correctly with edge cases in the inner loop. When j == 19, you access a[j+1], which is a[20], which is beyond the end of the array. You thus import garbage data into your array.

Lastly, even after correcting the above, your implementation is needlessly inefficient, in that your inner loop goes through the entire array on each iteration of the outer loop, which it doesn't have to. Hint: Try to think about how the initialization or termination condition of the inner loop could depend on i.

Update (after the OP's rewrite): You only addressed the second issue.

Upvotes: 6

bolov
bolov

Reputation: 75894

int main() {
    int a[20];
    srand(time(0));

    // array values initialization
    for (int i = 0; i < 19; i++) {
        a[i] = rand() % (81);
    }

    // array sorting
    bsort(a);

    // array printing
    for (int i = 0; i < 19; i++) {
        printf("%3d", a[i]);
    }
}

Upvotes: 1

Related Questions