How to find and display, for example, three maximum or minimum elements of an array, in the C programming language? For example, an array
char mas[] = { 8, 7, 3, 9, 5, 2}; and to output (3 max.) 9 8 7.
You can define a function that will find any number of maximal elements in an integer array. To do this, you just need to pass to the function an array of the required dimension for storing maximum values.
The function returns the number of maximum elements, since in general you can request to find more maximum elements than the total number of elements is in the array, or, for example, when an empty array is passed to you.
Below is a demo program.
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> size_t max_elements(const int *a, size_t n, int *max, size_t m) { size_t k = 0; for (size_t i = 0; i < n; i++) { size_t j = 0; while (j < k && !(a[i] > max[j])) j++; if (j == k ) { if ( k < m ) max[k++] = a[i]; } else { memmove(max + j + 1, max + j, ( k < m ? k - j: k - j - 1 ) * sizeof(int)); max[j] = a[i]; if (k < m) ++k; } } return k; } #define N1 10 #define M 3 int main() { int a[N1]; int max[M]; srand((unsigned int)time(NULL)); for (size_t i = 0; i < N1; i++) a[i] = rand() % (2 * N1); for (size_t i = 0; i < N1; i++) printf("%d ", a[i]); printf("\n"); size_t k = max_elements(a, N1, max, M); if (k != 0) { printf("%zu max elements are ", k); for (size_t i = 0; i < k; i++) printf("%d ", max[i]); printf("\n"); } } Its output to the console might look like this:
13 17 8 9 14 10 2 15 3 19 3 max elements are 19 17 15 Similarly, you can find the minimum items. All you need to do is change the condition in this cycle.
while (j < k && !(a[i] > max[j])) j++; ^^^^^^^^^^^^^^^^ As an option -
void max3(int * a, int N) { int i, retry; for(i = 0; i < N-3; ++i) { for(retry = 1; retry;) { retry = 0; for(int j = N-1; j >= N-3; --j) { if (a[i] > a[j]) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; retry = 1; break; } } } } } int main(int argc, const char * argv[]) { int a[] = { 3, 5, 7, 1, 9, 2, 8, 0, 1, 9 }; max3(a,sizeof(a)/sizeof(a[0])); for(int j = sizeof(a)/sizeof(a[0])-3; j < sizeof(a)/sizeof(a[0]); ++j) { printf("%3d",a[j]); } printf("\n"); } About efficiency - well, O (n), because 3 is a constant :)
Source: https://ru.stackoverflow.com/questions/599099/
All Articles
{5, 5, 5, 1, 2, 3}. By the way, what is the correct result in this case5, 5, 5or5, 3, 2? - andy.37