Which interrupt first

Several devices can raise an interrupt at the same moment. The CPU serves the most urgent first, and every interrupt has a priority for that. In this exercise a smaller number means more urgent.

What to build

Given the priorities of interrupts that are all pending at once, print the order in which the CPU serves them.

Requirements

  • Interrupt Ii is the i-th one in the list (counted from 1). Serve the pending interrupt with the smallest priority number first. Equal priorities: the one listed first.
  • Print order: followed by the interrupts in the order they are served, such as order: I3 I1 I2.

Input

The first line has n (1 ≤ n ≤ 20). The second line has the n priority numbers (0 to 15).

Output

One line: order: and the interrupts in service order.

Constraints

Each interrupt runs to the end before the next one starts.

Example

Input:

3
5 1 3

Output:

order: I2 I3 I1

Why it works

A device with a deadline, such as a disk or a network card, gets a small number so the CPU looks at it first. Breaking ties by arrival keeps the order fair and the same on every run.

Examples

Example 1 · Input
3
5 1 3
Expected output
order: I2 I3 I1
Example 2 · Input
4
2 2 1 2
Expected output
order: I3 I1 I2 I4

Hints

Hint 1

Selection by hand: repeat n times, pick the unserved interrupt with the smallest priority number; a tie goes to the one listed first.

Hint 2

Keep a served[] array, like the SSTF exercise.

Hint 3

Print the names as I1, I2, ... using the position in the list, counted from 1.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>

int main(void) {
    int n, pri[20], served[20] = {0};
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", &pri[i]);
    printf("order:");
    for (int k = 0; k < n; k++) {
        int best = -1;
        for (int i = 0; i < n; i++)
            if (!served[i] && (best < 0 || pri[i] < pri[best])) best = i;
        served[best] = 1;
        printf(" I%d", best + 1);
    }
    printf("\n");
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Input, output and interrupts →