write a program to find the median of a user-defined array using bubble sort
#include<stdio.h>
double calculateMedian(int elements[], int n){
if (n % 2 != 0){
return (double)elements[n / 2];
}
return (double)((double)elements[(n - 1) / 2] + (double)elements[n / 2]) / 2.0;
}
void bubbleSort(int elements[],int n){
int i,j;
for (i = 0; i < n - 1; i++){
for (j = 0; j < n - i - 1; j++){
if (elements[j] > elements[j + 1])
{
// swap temp and elements[i]
int temp = elements[j];
elements[j] = elements[j + 1];
elements[j + 1] = temp;
}
}
}
}
void printArray(int elements[],int n){
int i;
for(i=0; i<n; i++){
printf("%d ", elements[i]);
}
}
int main(){
int i,j;
int n;
int elements[1000];
printf("Enter the number of elements: ");
scanf("%d",&n);
for( i=0; i<n; i++){
printf("Enter element %d: ", (i+1));
scanf("%d", &elements[i]);
}
printf("\nThe elements of the array are:\n");
printArray(elements,n);
bubbleSort(elements,n);
printf("\nThe array after sorting the elements:\n");
printArray(elements,n);
printf("\nThe median of the array is: %.2f",calculateMedian(elements,n));
getchar();
getchar();
return 0;
}
Comments
Leave a comment