|
| 1 | +from heapq import heapify, heappop, heappush |
| 2 | + |
| 3 | +""" |
| 4 | +Shortest Job First (SJF) is a scheduling algorithm that selects the waiting process with the smallest execution time to execute next. |
| 5 | +This algorithm can minimize the average waiting time of processes in the queue and is often used in batch processing systems. |
| 6 | +The implementation of SJF involves sorting the processes by their execution time and selecting the process with the shortest execution time first. |
| 7 | +This is known as the non-preemptive SJF algorithm. |
| 8 | +In preemptive SJF, the algorithm can interrupt an executing process and switch to a shorter job, if one becomes available. |
| 9 | +Here is an example implementation of the non-preemptive SJF algorithm in Python. |
| 10 | +""" |
| 11 | + |
| 12 | + |
| 13 | +def main(): |
| 14 | + |
| 15 | + # Tasks given with their arrival time and their processing time |
| 16 | + tasks = [[1, 2], [2, 4], [3, 2], [4, 1]] |
| 17 | + # an array to hold tasks while the CPU is executing |
| 18 | + currTasks = [] |
| 19 | + # an array to hold the order of tasks |
| 20 | + orderedTasks = [] |
| 21 | + |
| 22 | + # an a rray to hold the index of each task |
| 23 | + for index, task in enumerate(tasks): |
| 24 | + task.append(index) |
| 25 | + |
| 26 | + # make heap of the tasks in order to find the shortest task in the first index |
| 27 | + heapify(tasks) |
| 28 | + |
| 29 | + # start from the first task and add it to the currTasks array |
| 30 | + task = heappop(tasks) |
| 31 | + time = task[0] |
| 32 | + currTime = time + task[1] |
| 33 | + orderedTasks.append(task[2]) |
| 34 | + |
| 35 | + while tasks: |
| 36 | + # when the CPU is currently busy and tasks are incoming hold them in currTasks |
| 37 | + while tasks and tasks[0][0] <= currTime: |
| 38 | + start, duration, index = heappop(tasks) |
| 39 | + heappush(currTasks, [duration, index, start]) |
| 40 | + |
| 41 | + # if the CPU is idle and tasks are incoming add them to currTasks |
| 42 | + if not currTasks: |
| 43 | + start, duration, index = heappop(tasks) |
| 44 | + currTime = currTime + duration + start |
| 45 | + orderedTasks.append(index) |
| 46 | + # if there are tasks in queue to be preocessed in currTasks, pop the shortest procssing time and add them to the orderedTasks because they are being excuted by the CPU |
| 47 | + else: |
| 48 | + duration, index, start = heappop(currTasks) |
| 49 | + currTime += duration |
| 50 | + orderedTasks.append(index) |
| 51 | + |
| 52 | + # if there are tasks left in the queue execute them accordingly |
| 53 | + while currTasks: |
| 54 | + duration, index, start = heappop(currTasks) |
| 55 | + orderedTasks.append(index) |
| 56 | + |
| 57 | + return orderedTasks |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + print("Order of Tasks: ", main()) |
0 commit comments