What are the pros and cons of this code? /**************************************
ID: 3866304 • Letter: W
Question
What are the pros and cons of this code?
/*********************************************************************
** Description: This program takes an array and finds and returns the median of it.
*********************************************************************/
#include
using namespace std;
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
cout<
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
int findMedian(int arr[], int n){
//printArray(arr, n);
// calling sort
selectionSort(arr, n);
//printArray(arr, n);
return arr[n/2]; // median
}
int main()
{
/*
int arr[] = {23, 25, -10, 0, -46, 321, 15, -32, 50, 1, 2, 99, 30};
int n = 13;
int m = findMedian(arr, n);
cout<<"Medain: "<< m < */
return 0;
}
Explanation / Answer
1) we can find the array length by using sizeof() operator that is sizeof(array)/size(int) will give you the array length no needt to pass one more parameter to selection sort.
2)Instead of selection sort we can use quick sort which is more efficeint sort thant selection sort most of the time
3)for odd length of array the media is n/2 th element but if the array length is even we need to take average of middle two numbers
4)printArray funtion is not fully implemented
5) Even for printing the array also one arugment is sufficient
6)samle code to find the size of array is
int main()
{
int arr[] = {1, 2, 3, 4, 7, 98, 0, 12, 35, 99, 14};
printf("Number of elements :%d", sizeof(arr)/sizeof(arr[0]));
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.