In: Computer Science
The programming language is C.
In its simplest algorithm, the bubble sort technique compares each two adjacent elements of an array of size “N” and exchanges their values if they are out of order. The process of comparing and exchanging is repeated for N array passes. For sorting array elements in ascending order, the smaller values “bubble” to the top of the array (toward element 0), while the larger values sink to the bottom of the array. Assuming that: double ArrayA[ ] = {100.1, 99.2, -8.7, 23.3, -19, 11.2, 20.6, 27.7, -1.1, 13.1, 12.6, 15.9, 55.1, -40.2, 0 } is stored in memory. Write a complete C language program that sorts ArrayA in ascending order using bubble sort technique. Your program should display the array before and after sorting. Your answer should include screenshots of your code and program outputs. Your programs should be properly commented.
Source Code:
#include <stdio.h>
void bubbleSort(double arr[],int n)
{
double temp=0.0;
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
void printArray(double arr[],int n)
{
for(int i=0;i<n;i++){
printf("%.2lf ",arr[i]);
}
printf("\n");
}
int main()
{
double ArrayA[ ] = {100.1, 99.2, -8.7, 23.3, -19,
11.2, 20.6, 27.7, -1.1, 13.1, 12.6, 15.9, 55.1, -40.2, 0 };
int len=sizeof(ArrayA)/sizeof(ArrayA[0]);
printf("Before sorting:\n");
printArray(ArrayA,len);
bubbleSort(ArrayA,len);
printf("After sorting:\n");
printArray(ArrayA,len);
}
Sample input and output: