简体   繁体   中英

Search for the biggest number/s in an integer Array in C

This continues from my previous question .

I have an array, and want to find the biggest numbers in it. But I can't sort then, 'cause is very important indexes of the numbers, so the can't be moved. And finally, the output of my problem should be "the biggest number/s are in index 1 and 4, with the number 8. Here is the array:

int anonarray[5] = {3,8,7,5,8};
enum { MAX_ENTRIES = 5 };
int anonarray[MAX_ENTRIES] = { 3, 8, 7, 5, 8 };
int maxval = anonarray[0];
int maxidx[MAX_ENTRIES] = { 0, 0, 0, 0, 0 };
int maxnum = 1;

for (int i = 1; i < MAX_ENTRIES; i++)
{
    if (maxval < anonarray[i])
    {
        /* New largest value - one entry in list */
        maxval = anonarray[i];
        maxnum = 1;
        maxidx[0] = i;
    }
    else if (maxval == anonarray[i])
    {
        /* Another occurrence of current largest value - add entry to list */
        maxidx[maxnum++] = i;
    }
}

printf("The biggest number is in %s", ((maxnum > 1) ? "indices" : "index"));
const char *pad = " ";
for (int i = 0; i < maxnum - 1; i++)
{
    printf("%s%d", pad, maxidx[i]);
    pad = ", ";
}
printf(" %s%d, with value %d.\n", ((maxnum > 1) ? "and " : ""),
       maxidx[maxnum-1], maxval);

Note that internationalizing that English-specific formatting will not necessarily be easy!

Loop through the array to find the maximum:

int max = a[0], count = 0;

for(i=1;i<n;i++)
  if(max<a[i]) 
     max=a[i]; 

for(i=0;i<n;i++)
  if(max==a[i]) 
     count++; //num of maximums

Now declare an array to store the indexes:

int index[count], j=0;

for(i=0;i<n;i++)
{
 if(a[i]==max)
   index[j++]=i;
}

Now index has the list of indexes which have the element max .

This is asymptically O(n) and tkaes the least possible memory.

This can be solved by using the technique of sorting an array of pointers. Something like:

int a[5] = {3,8,7,5,8};
int *pa[5];
for (int i = 0; i < 5; i++) {
    pa[i] = &a[i];
}
sort(pa); // pseudocode, be sure to sort by what pa[i] points to
for (int i = 0; i < 5; i++) {
    printf("n=%d index=%d\n", *pa[i], pa[i] - a);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM