22:14 -
Data Structures using C
Write a function in C to sort a single dimensional array of 10 integers using Bubble Sort technique.
#include<stdio.h>
#define
MAX 10
/*function
for sorting using bubble sort*/
void
bubble_sort(int a[];int n)
{
int i; /*to access subsequent item while
comparing*/
int j; /*keep track of passes*/
int temp; /*used to exchange the item*/
int sum; /*holds the total number of passes
required*/
int exchag /*holds the number of exchanges
in each pass*/
int flag; /*indicate any exchange has been
done or not*/
sum=0,pass=0;
for(j=1;j<n;j++)
{
exchg=0;/*no. of exchange just before
the pass*/
flage=0; /*no exchange been done*/
for(i=0;i<n-j;i++)
{
if(a[i]>=[a[i+1])
{
/*Exchange
and update the number of exchange int current pass*/
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
exchg++;
sum++ /*Update the total number of
exchanges*/
flag=1 /*Exchange has been done*/
}
}
pass++; /*update the number of passes*/
printf(“Number of exchanges in pass : %d=%d\n”,j,exchg);
printf(“Total number of exchanges= %d\n”,
sum)
}
/*Function Ends Here*/
/*main
function*/
void
main()
{
int i, a[MAX];
printf(“Enter the items to sort\n”);
for(i=0; i<MAX; i++)
{
scanf(“%d”, &a[i]);
}
/*call bubble_sort function for sorting*/
bubble_sort(a,MAX);
/*print the sorted array*/
printf(“The sorted items are \n”);
for(i=0;i<MAX;
i++)
{
printf(“%d \n”,a[i]);
}
}