数组中的多数元素。它

时间:2017-07-05 03:20:17

标签: c

#include <stdio.h>

void main()
{
    int maj, count, n = 6;
    int arr[] = {1, 2, 2, 2, 2, 3, 4};

    for (int i = 0; i < n; i++) {
        maj = arr[i];
        count = 0;
        for (int j = 9; j < n; j++) {
            if (arr[j] == maj) count++;
        }
        if (count > n / 2) {
            break; /* I think some problem is here ,if majority element not found then it takes last element as the majority element */
        }
    }
    printf("%d", maj);
}

如果存在多数元素,则给出正确的输出但是如果没有多数元素则输出不正确,例如如果数组是{1,2,3,4}则输出为4.请帮助!!

2 个答案:

答案 0 :(得分:0)

#include <stdio.h>
int main() {
    int maj, count, n = 7; //n is size of arr
    int arr[] = {1, 2, 2, 2, 2, 3, 4};
    int isFound = 0; //0 -> false, 1 -> true

    for (int i = 0; i < n; i++) {
        maj = arr[i];
        count = 1;  //first elements is itself
        isFound = 0;  //by default we assume that no major elements is found

        for (int j = i+1; j < n; j++) { //iterate from next elements onwards to right in array
            if (arr[j] == maj) count++;
        }
        if (count > n / 2) {
            isFound = 1;
            break; //major elements found; no need to iterator further; just break the loop now
        }
    }
    if(isFound)   printf("%d ", maj);
    else printf("no major element");
    return 0;
}

答案 1 :(得分:0)

对于根据C标准函数的启动器,没有参数的main应声明为

int main( void )

尽量不要使用魔术数字。通常在程序中,它们是程序错误的原因。例如,您将数组arr声明为具有7个元素,但是应该保留数组中元素数量的变量n使用值6进行初始化。循环中使用了另一个幻数9

for (int j = 9; j < n; j++) {
            ^^^

无需编写遍历整个数组的外部循环。当数组中不存在多数时,程序也不会报告该情况。

使用两个循环的方法,程序可以按以下方式查看

#include <stdio.h>

int main( void ) 
{
    int a[] = { 1, 2, 2, 2, 2, 3, 4 };
    const size_t N = sizeof( a ) / sizeof( *a );

    size_t i = 0;
    for ( ; i < ( N + 1 ) / 2; i++ )
    {
        size_t count = 1;
        for ( size_t j = i + 1; count < N / 2 + 1 && j < N; j++ )
        {
            if ( a[i] == a[j] ) ++count;
        }

        if ( !( count < N / 2 + 1) ) break;
    }

    if ( i != ( N + 1 ) / 2 )
    {
        printf( "The majority is %d\n", a[i] );
    }
    else
    {
        puts( "There is no majority element" );
    }

    return 0;
}

它的输出是

The majority is 2