SCAN (Elevator) Algorithm in Java — Single Elevator Scheduling Explained
In real buildings, elevators do not serve floor requests in the order they arrive. Instead, they use a smart scheduling strategy known as the SCAN Algorithm, also called the Elevator Algorithm.
This algorithm is also used in operating systems for disk scheduling and is designed to minimize unnecessary movement while ensuring fairness.
What Is the SCAN (Elevator) Algorithm?
The SCAN algorithm works just like a real elevator:
- The elevator moves in one direction (UP or DOWN).
- It serves all requests in that direction.
- When it reaches the last request or end floor, it reverses direction.
This prevents random zig-zag movement and improves efficiency.
Problem Scenario
Assume:
- Elevator is currently at floor 5
- Direction: UP
- Floor requests: 1, 3, 4, 7, 9
How SCAN Works Here
The elevator first serves all requests above floor 5, then reverses.
- Move UP → 7 → 9
- Reverse direction
- Move DOWN → 4 → 3 → 1
Service Order: 7 → 9 → 4 → 3 → 1
Java Program — SCAN Algorithm (Single Elevator)
import java.util.*;
public class ElevatorSCAN {
public static void main(String[] args) {
int currentFloor = 5;
String direction = "UP";
List requests = Arrays.asList(1, 3, 4, 7, 9);
List up = new ArrayList<>();
List down = new ArrayList<>();
for (int floor : requests) {
if (floor >= currentFloor) {
up.add(floor);
} else {
down.add(floor);
}
}
Collections.sort(up);
Collections.sort(down, Collections.reverseOrder());
System.out.println("Elevator Service Order:");
if (direction.equals("UP")) {
for (int floor : up) {
System.out.println("Serving floor " + floor);
}
for (int floor : down) {
System.out.println("Serving floor " + floor);
}
} else {
for (int floor : down) {
System.out.println("Serving floor " + floor);
}
for (int floor : up) {
System.out.println("Serving floor " + floor);
}
}
}
}
Sample Output
Elevator Service Order:
Serving floor 7
Serving floor 9
Serving floor 4
Serving floor 3
Serving floor 1
Why SCAN Is Better Than FIFO
- Reduces total elevator movement
- Prevents starvation
- More realistic and efficient
Practice Challenges
- Modify the program to take input from the user.
- Add a building floor limit (e.g., 0–10).
- Calculate total elevator movement (distance traveled).
The SCAN algorithm is a perfect example of how computer science concepts directly apply to real-world systems like elevators and disk scheduling.