Saturday, 26 January 2019

PROGRAM TO IMPLEMENT BUBBLE SORT C - using function



BUBBLE SORT C USING FUNCTION:

Executable bubble sort program download link available at the end of this page. This bubble sort c program uses function, first of all we discuss what is SORT, sort is a arranging the element either ascending order or descending order. Bubble sort is the simplest sorting algorithm it sort adjacent element until it become either ascending or descending.



Example:

(4,1,2,6)   // is a given number

(4,1,2,6)  // check  (4>1)..?  YES swap 4 and 1

(1,4,2,6)  // check (4>2)..? YES  swap 4 and 2
(1,2,4,6)  // check (4>6)..? NO don’t swap.

Element of 4,1,2,6 after sorting 1,2,4,6

Let’s See another Example for your clarity.

(3,1 7,8,10,5,2) // Consider as Given number

Pass 1:
(3,1,7,8,10,5)  // if(3>1)…?? Yes .,  Swap it.
(1,3,7,8,10,5)  // if (3>7)..? False ..
(1,3,7,8,10,5) // if(7>8)..? false..
(1,3,7,8,10,5) // (8>10)..?  False…
(1,3,7,8,10,5)//(10>5)..? Yes  Swap it
(1,3,7,8,5,10)  // 1st  completed

Pass 2:
 (1,3,7,8,5,10)   // Pass 1 result
(1,3,7,8,5,10) //(1>3)..? False
(1,3,7,8,5,10) //(3>7)..? False
(1,3,7,8,5,10) // (7>8)..? False
(1,3,7,8,5,10) // (8>5)..? Yes… Swap it
(1,3,7,5,8,10) //(8<10)..? False
(1,3,7,5,8,10) // 2nd pass result

Pass 3:

(1,3,7,5,8,10) // (1>3)..?? False
(1,3,7,5,8,10) // (3>7)….? False
(1,3,7,5,8,10) // (7>5)..?  Yes  Swap it
(1,3,5,7,8,10)  //(7>8)..? False
(1,3,5,7,8,10) // (8>10)..? False

(1,3,5,7,8,10)  // 3rd Pass Result

(3,1,7,8,10,5)  Result After Sorting is  (1,3,5,7,8,10)  



#include<stdio.h>
void bubble_sort(int [], int);

int main()

{
int array[100],n,i,j;

printf("enter the number of element to be enetered\n");
scanf("%d",&n);

printf("Enter the element\n");
for(i=0;i<n;i++)
scanf("%d",&array[i]);

bubble_sort(array,n);

printf("sorted list in ascending order");
for(i=0;i<n;i++)
printf("%d\t",array[i]);
return 0;
}

void bubble_sort(int array[], int n)
{
int i,j,k;
for(i=0;i<n-1;i++)
 {
  for(j=0;j<n-i-1;j++)
    {
     if(array[j] > array[j+1])
        {
 //swapping

k = array[j];
array[j] = array[j+1];
array[j+1]=k;
}
}
}
}


Output:

 

Executable C file Link:

Download


No comments:

Post a Comment