Monday, October 19, 2015

Bubble Sort with Function

/* Bubble sort code with function */

#include <stdio.h>

#define MAX 1000000



int main()
{
    int array[MAX];
    int n,a,b,swap;
   
    printf("\n Enter number of elements\n");
    scanf("%d", &n);
    /* placed number of elements, n, in address &n */
   
    printf("\nEnter number of integers %d \n", n);
   
    for (a=0;a<n;a++)
    {
        scanf("%d",&array[a]);
       
        /* Input array elements into their address locations */
    }


    printf("\nSorted list in ascending order:\n");   
    sort(n,array); 
   
    printf("\n\n\nEnd Sort \n");
   
    return 0;
}

int sort(int num,int x[])
{   int a, b, j, swap;
   
    for (a=0;a<(num-1);a++)
    {
        for (b =0;b<num-a-1;b++)
        {
            if (x[b] > x[b+1]) /* For decreasing order use < */
            {
                swap=x[b];
                x[b]=x[b+1];
                x[b+1]=swap;
            }
        }
    }
    
    for (j=0;j<num;j++ )
    {
        printf("%d\n", x[j]);
    }
     
}

No comments:

Post a Comment