Problem overview
The previous version found the single best brand. This version prints the top k brands in rank order, without sorting anything. The data is two parallel arrays, brands and ratings, where ratings[i] belongs to brands[i], plus an int named k. Each output line has the form rank. Brand (rating), starting at rank 1. Ties go to the brand listed first, and k is never larger than the number of brands.
The starter data has five brands: TechPro 4, MegaCorp 5, Quantum 3, NeoByte 5 and Zenith 4, with k = 3. MegaCorp and NeoByte tie at 5, and MegaCorp comes first. TechPro and Zenith tie at 4, and TechPro comes first. The output is:
1. MegaCorp (5)
2. NeoByte (5)
3. TechPro (4)
Approach: search, mark, search again
Finding the best brand is a loop with a "best so far" index: start with nothing chosen, visit every position, and replace the choice only when a rating is strictly higher. Strictly higher is what gives the tie rule, because an equal rating never pushes out the brand found earlier.
To get the second best, run the same search again, but ignore the brand that already won. A bool array named used, with one flag per brand, records who is taken. The search considers only brands whose flag is still false. After every round, the winner's flag becomes true, so the next round finds the best among the rest. Doing this k times produces the brands in rank order.
This is a pair of nested loops. The outer loop counts the ranks, and the inner loop scans all the brands for each rank. The work is about k times n comparisons, which is fine for a few brands. Sorting is not needed, and the original arrays stay in their original order.
Tracing the example: in round 1 the search sees TechPro (4), then MegaCorp (5) replaces it, and nothing later beats 5, so MegaCorp wins. In round 2, MegaCorp is skipped, so TechPro is the first candidate, Quantum (3) does not beat it, NeoByte (5) does, and Zenith (4) does not beat 5. NeoByte wins. In round 3 only TechPro (4), Quantum (3) and Zenith (4) are left. TechPro is found first and Zenith's 4 is not strictly higher, so TechPro takes third place.
Step by step
- Create
usedasnew bool[ratings.Length]. C# fills a newboolarray withfalse, which means nobody is taken yet. - Create
linesas an emptyList<string>. Each round adds one finished line, and the list grows as needed, which an array could not do. - Write the outer loop with
rankfrom 1 up to and includingk. Starting at 1 means the same variable is also the number printed in front of the brand. - Create
bestIndexat -1 inside the loop. No brand has index -1, so it means that nothing has been found in this round. Declaring it inside the outer loop restarts the search every round. - Write the inner loop over
ifrom 0 toratings.Length. Each round looks at every brand again. - Skip taken brands. The first
ifis!used[i]: only brands that have not won are candidates. - Test the candidate. The second
ifis true when nothing is chosen yet (bestIndex == -1) or the rating is strictly higher than that ofbestIndex. - Remember it with
bestIndex = i. The position is enough, since the name and the rating are read from it later. - Mark the winner after the inner loop:
used[bestIndex] = true. It happens right away, because the next round reads the flag. - Build the line with
rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ")"and add it tolines. - Print after the loop with
string.Join("\n", lines)insideConsole.WriteLine, which puts a newline between every two lines.
The solution in C#
string[] brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
int[] ratings = {4, 5, 3, 5, 4};
int k = 3;
bool[] used = new bool[ratings.Length];
List<string> lines = new List<string>();
for (int rank = 1; rank <= k; rank++) {
int bestIndex = -1;
for (int i = 0; i < ratings.Length; i++) {
if (!used[i]) {
if (bestIndex == -1 || ratings[i] > ratings[bestIndex]) {
bestIndex = i;
}
}
}
used[bestIndex] = true;
lines.Add(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");
}
Console.WriteLine(string.Join("\n", lines));
Details worth knowing:
- Short-circuit
||. InbestIndex == -1 || ratings[i] > ratings[bestIndex], whenbestIndexis -1 the right side is never evaluated. That protectsratings[-1], which would throw anIndexOutOfRangeException. intplusstring. Inrank + ". " + ...the first+has aninton the left and a string on the right, so C# turns the number into text and concatenates. What matters is where the string enters the expression:1 + 2 + ". x"gives3. xbecause the numbers are added first, while". x" + 1 + 2would give. x12.List<T>andusing.List<string>lives inSystem.Collections.Generic, so a standalone file needsusing System.Collections.Generic;. Its size isCount, andAddappends at the end.string.Join. It glues the elements of any sequence of strings together with a separator between them and none at the end. For an empty list the result is an empty string, soConsole.WriteLineprints a single blank line.- Arrays start as defaults. A new
bool[n]holdsfalsein every slot, a newint[n]holds 0, and a newstring[n]holdsnull.
Complexity
Let n be the number of brands.
Time: O(k * n). The outer loop runs k times, and each round scans all n positions with constant work per position. Since k is at most n, the worst case is O(n^2), reached when k equals n and the search effectively becomes a selection sort that writes down the order. Sorting once and taking the first k would cost O(n log n).
Space: O(n + k). The used array has n flags and lines holds k strings.
Edge cases and common mistakes
- Ties. With the starter data, NeoByte follows MegaCorp and TechPro precedes Zenith, because every comparison is strictly greater. Writing
>=would let the later brand of each tie replace the earlier one, and the output would start with1. NeoByte (5). kequal to the number of brands. Withk = 5every brand is printed once, ending with5. Quantum (3). Zenith comes fourth, after TechPro, because they tie at 4.k = 1. The program prints only1. MegaCorp (5), which is the previous version's result.klarger than the number of brands. The lesson promises this does not happen. If it did, the extra round would find nothing,bestIndexwould stay -1, andused[bestIndex]would throw anIndexOutOfRangeExceptionwith the message "Index was outside the bounds of the array."- Forgetting to mark the winner. Every round would pick the same brand, and the output would repeat it
ktimes with different ranks. - Declaring
bestIndexoutside the outer loop. It would start the next round on the previous winner, who is already taken. No remaining brand has a strictly higher rating, so that index never changes and the output repeats the first winner with new ranks. - Starting the rank at 0. The lines would read
0. MegaCorp (5). The lesson numbers from 1.
Testing
- The starter data with
k = 3prints the three lines shown at the top. - With
k = 1only1. MegaCorp (5)prints. - With
k = 5the lines are MegaCorp (5), NeoByte (5), TechPro (4), Zenith (4) and Quantum (3), numbered 1 to 5.
The next version builds on this one.
