Array Sorting (Bubble Sort)

Bubble sort is a basic sorting algorithm that repeatedly steps through the list, swapping adjacent elements if they are in the wrong order.

Suppose we have an array with its lower limit L and upper limit U which is to be sorted in order using bubble sort.

Algorithm

INPUT : ARRAY A[L…U]
OUTPUT: SORTED ARRAY
DATA STRUCTURE: SINGLE DIMENSIONAL ARRAY

STEP 1:  START
STEP 2: FOR( I=1 TO I=N-1)DO
STEP 3: FOR(J=1 TO N-1)DO
STEP 4: IF(A[J]>A[J+1])
STEP 5: ENDIF
STEP 6: ENDFOR
STEP 7: ENFOR
STEP 8: STOP

Code

#include <stdio.h>
int bubblesort();
int a[]={1,5,3,2,1};
int main()
{
int n,pos=0;
pos=bubblesort();
printf("THE SORTED ARRAY IS:");
for(int i=0;i<5;i++)
{
printf("%d ",a[i]);
}
return 0;
}
int bubblesort()
{
int i,flag=0,pos=-1;
for(int i=0;i<5-1;i++)
{
for(int j=0;j<5-i-1;j++)
{
if(a[j]>a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
return 0;
}

Output

user@computer$ : THE SORTED ARRAY IS:1 1 2 3 5

Click here to get the algorithm and the code in C for linear searching in an array.

Click here to get the algorithm and the code in C for array traversal.

1 thought on “Array Sorting (Bubble Sort)”

  1. Pingback: Algorithm and Code for Array Searching (Linear Search) - Ultimate Coder

Leave a Comment

Your email address will not be published. Required fields are marked *