In: Computer Science
The following flow chart is a bubble sort. Write the code for this sort. Make sure you display each pass and comparison. Include comments.
OUTPUT
CODE FOR BUBBLE SORT
PSEUDOCODE
n->Number of elements of the array
Step-1 I=0
Repeat through step 3 while (I<n)
Step-2 j=0
Repeat through step 3 while j<n-I
Step-3 if arr[j]<arr[j+1]
Temp = arr[j]
arr[j+1] = arr[j]
arr[j]=temp
Step-4 exit
PROGRAM
#include <stdio.h>
#include <stdlib.h>
void main()
{
int arr[10],i,j,temp; //variable declaration
//loop to input the numbers into array
for (i = 0; i < 10; i++)
{
printf("\nENTER A NUMBER");
scanf("%d",&arr[i]);
}
//display elements before sort
printf("\n Array elements are : \n");
for (i=0;i<10;i++)
printf("%5d",arr[i]);
//logic for bubble sort
for (i = 0; i < 10; i++)
for (j = 0; j < 10-i; j++)
if (*(arr+j) > *(arr+(j+1))) //compare an element
with its next element
{ //swap two
numbers
temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
//display the sorted list
printf("\n Sorted list is as follows\n");
for (i=0;i<10;i++)
printf("%5d",arr[i]);
}
OUTPUT
EXAMPLE