Tìm phần tử xuất hiện nhiều nhất trong mảng các số nguyên.

Yêu cầu:

Viết hàm tìm phần tử xuất hiện nhiều nhất trong mảng các số nguyên.

Thuật toán:

Viết hàm tìm phần tử xuất hiện nhiều nhất trong mảng các số nguyên.

Code:

/************************************************************
* Author: VNCODING
* History 
* 2014/11/17 first create VNCODING
*************************************************************/
#include "stdio.h"
#include "conio.h"
#include "string.h"

#define MAX_SIZE 100

void init_array(int A[], int n, int x);
void find_elmnt_appear_most(int A[], int B[], int n);
int max_arr(int A[], int n);


void main( void )
{
    int A[] = {5, 10, 6, 1, 5, 4, 6, 5, 6, 1, 6, 1, 1};
    int n = sizeof(A)/sizeof(int);

    // using array B to store the number of appearance time of the element.
    int B[MAX_SIZE];
    init_array(B, n, 1);
    find_elmnt_appear_most(A, B, n);

    getch();
}

// initialize array
void init_array(int A[], int n, int x)
{
    int i;
    for(i = 0; i < n; i++)
    {
        A[i] = x;
    }
}

//Find elements appear most
void find_elmnt_appear_most(int A[], int B[], int n)
{
    int i, j;
    int res_max;
    for(i = 0; i < n - 1; i++)
    {
        for(j = i+1; j < n; j++)
        {
            if(B[i] == -1)
                continue;
            if(A[i] == A[j])
            {
                (B[i])++;
                B[j] = -1;
            }
        }
    }
    // get the maximum appearance of element
    res_max = max_arr(B, n);
    printf("\nThe elements appear most time is: ");
    for(i = 0; i < n; i++)
    {
        if(B[i] == res_max)
        printf("%d, ", A[i]);
    } 
}

//Find maximum element
int max_arr(int A[], int n)
{
    int i;
    int max = A[0];
    for(i = 1; i < n; i++)
        if(max < A[i])
            max = A[i];

    return max;
}

Kêt quả:

The elements appear most time is: 6, 1,

Be the first to comment

Leave a Reply