Bubble sort in an Array.
Bubble Sort is the simplest sorting that works by repeatedly swapping the adjacent elements of array if they are in wrong order.
Algorithm of Bubble Sort in an Array
Bubblesort(A,N) – Given a one-dimensional array A with N elements. This algorithm sorts the array A according to the bubble sort technique.
Step1. START
Step2. Repeat Step 3 for I <- 1 to N-1[Number of Passes]
Step3. Repeat Step 4 for J <- 1 to N-I
Step4. If(A[J]>A[J+1]) then [Comparing adjacent elements]
(a) TEMP <- A[J]
(b) A[J] <- A[J+1]
(c) A[J+1] <- TEMP
[end of If Structure]
[end of step 3 loop]
[end of step 2 loop]
Step5. END
Program of Bubble Sort in an Array.
#include<stdio.h>
#include<conio.h>
void main()
{
int array[100], n, i, j, temp;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d Numbers:\n", n);
for(i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
for(i = 0 ; i < n - 1; i++)
{
for(j = 0 ; j < n-i-1; j++)
{
if(array[j] > array[j+1])
{
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
printf("Sorted Array:\n\n");
for(i = 0; i < n; i++)
{
printf("%d\n", array[i]);
}
getch();
}//end of main function