Нужно написать программу, которая обнаруживает 2 наименьших (минимум) и 2 наибольших (максимальных) элемента из одномерного массива из десяти чисел, введенных в двоичном коде (макс. 8 бит), который программа считывает из файла. Он печатает все числа на экране вместе с их транскрипцией в десятичной системе, включая минимумы и максимумы.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 89
#define Z 10
void qs(long int *s_arr, int first, int last);
int dec2bin(int num);
int main()
{
// variables
char binArr[N];
char *end;
char ch = 0;
long int decArr[Z];
// opening a file and reading from it
FILE *f = fopen("01.txt", "rb");
while (!feof(f))
{
fgets(binArr, N, f);
}
printf("%s\n", binArr);
printf("---------------------------------\n");
fclose(f);
// decimal conversion
decArr[0] = strtol(binArr, &end, 2);
for (int i = 1; i < 10; i++)
{
decArr[i] = strtol(end, &end, 2);
}
// output binary numbers in decimal format
for (int i = 0; i < 10; i++)
{
printf("#%d - %d = %ld\n", i + 1, dec2bin(decArr[i]), decArr[i]);
}
// sorting an array
qs(decArr, 0, Z - 1);
// max and min output
printf("max#1= %d = %ld\n", dec2bin(decArr[Z - 1]), decArr[Z - 1]);
printf("max#2= %d = %ld\n", dec2bin(decArr[Z - 2]), decArr[Z - 2]);
printf("min#1= %d = %ld\n", dec2bin(decArr[0]), decArr[0]);
printf("min#2= %d = %ld\n", dec2bin(decArr[1]), decArr[1]);
}
int dec2bin(int num)
{
int bin = 0, k = 1;
while (num)
{
bin += (num % 2) * k;
k *= 10;
num /= 2;
}
return bin;
}
void qs(long int *s_arr, int first, int last)
{
if (first < last)
{
// the pivot element of the array is selected (l + r) / 2
int left = first, right = last, middle = s_arr[(left + right) / 2];
do
{
// splits into 2 elements which are <= and> = to the pivot element of the array
// two variables store the indices of the sorted chunk on the left side increases by 1 from the right side decreases by 1 to the middle of the array
// we move them to the meeting, that is, left ++, and right--. As long as left <middle and right> middle
// we have to swap them, that is, to throw small elements to the left, and large ones to the right
while (s_arr[left] < middle)
left++;
while (s_arr[right] > middle)
right--;
if (left <= right)
{
// as soon as the elements meet, we divide into 2 parts and do the same
int tmp = s_arr[left];
s_arr[left] = s_arr[right];
s_arr[right] = tmp;
left++;
right--;
}
} while (left <= right); // have we reached the end?
// recursion starts
qs(s_arr, first, right);
qs(s_arr, left, last);
}
}