This is a C Program to find k numbers cloest to median of S, S being a set of n numbers.
Here is source code of the C Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include<stdio.h>
#include<math.h>
#include<time.h>
#include<stdlib.h>
int N = 25;
int sequence[25];
void sort() {
int i, j, temp;
for (i = 1; i < N; i++) {
j = i;
temp = sequence[i];
while (j > 0 && temp < sequence[j - 1]) {
sequence[j] = sequence[j - 1];
j = j - 1;
}
sequence[j] = temp;
}
}
int getMedian() {
if (N % 2 == 0)
return ((sequence[N / 2 - 1] + sequence[N / 2]) / 2);
else
return sequence[N / 2];
}
int main(int argc, char **argv) {
int i, j;
for (i = 0; i < N; i++)
sequence[i] = rand() % (100 - 1 + 1) + 1;
sort();
printf("The Sequence is: ");
for (i = 0; i < N; i++)
printf("%d ", sequence[i]);
int median = getMedian();
printf("\nEnter the number of elements close to median you want: ");
int k;
scanf("%d", &k);
if (N % 2 == 0) {
i = N / 2 - 1;
j = N / 2;
} else {
i = N / 2 - 1;
j = N / 2 + 1;
}
int flag = 0;
int n;
for (n = 0; n < k; n++) {
if (median - sequence[i] < sequence[j] - median) {
printf("%d ", sequence[i]);
i--;
if (i == -1) {
n++;
flag = 1;
break;
}
} else {
printf("%d ", sequence[j]);
j++;
if (j == N) {
n++;
break;
}
}
}
while (n < k) {
if (flag == 1) {
printf("%d ", sequence[j]);
j++;
n++;
} else {
printf("%d ", sequence[i]);
i--;
n++;
}
}
}
Output:
$ gcc KCloseToMedian.c $ ./a.out The Sequence is: 1 3 5 6 25 28 28 35 37 42 43 46 54 59 62 63 65 68 70 79 82 92 92 93 96 Enter the number of elements close to median you want: 2 59 62
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Related Posts:
- Practice BCA MCQs
- Check Computer Science Books
- Practice Computer Science MCQs
- Apply for C Internship
- Apply for Computer Science Internship