これは私の前の質問の続きです。
私は配列を持っていて、その中で最大の数字を見つけたいと思っています。しかし、私は並べ替えることができません。これは数字の非常に重要なインデックスであるため、移動することはできません。そして最後に、私の問題の出力は、「最大の数字はインデックス 1 と 4 にあり、数字は 8 です。配列は次のとおりです。
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);
英語固有のフォーマットを国際化することは、必ずしも簡単ではないことに注意してください。
配列をループして最大値を見つけます。
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
次に、インデックスを格納する配列を宣言します。
int index[count], j=0;
for(i=0;i<n;i++)
{
if(a[i]==max)
index[j++]=i;
}
index
要素を持つインデックスのリストがありますmax
。
これは漸近的に O(n) であり、可能な限り最小のメモリです。
これは、ポインターの配列をソートする手法を使用して解決できます。何かのようなもの:
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);
}