C语言--查询数组中出现次数最多的元素

 

查询数组中出现次数最多的元素

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

int max_count_num(int * arr, int len);


int main()
{
	int arr[5] = {1, 1, 1, 3, 1 };

	max_count_num(arr, 5);

	return 0;
}


int max_count_num(int * arr, int len)
{
	int i, j;
	int m;
	int count;
	//定义次数存储数组
	int * max = (int *)malloc(sizeof(int) * len);
	if (max == NULL) {
		printf("malloc failed\n");
		exit(-1);
	}
	//数组初始化
	for (i = 0; i < len; i++) {
		max[i] = 0;
	}

	//对数组中的元素进行count
	for (i = 0; i < len; i++) {
		count = 0;
		for (j = i; j < len; j++) {
			if (arr[i] == arr[j]) {
				max[i]++;
			}
		}
	}

	//取出数组中元素的最大值
	m = 0;
	for (i = 0; i < len; i++) {
		if (max[m] < max[i]) {
			m = i;
		}
	}
	printf("出现次数最多的元素为:%d, 出现次数为:%d\n", arr[m],max[m]);

	return 0;
}

posted on 2018-11-05 21:37  ykyk_dba  阅读(4274)  评论(1编辑  收藏  举报

导航