{"id":974,"date":"2025-08-22T11:32:43","date_gmt":"2025-08-22T06:02:43","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=974"},"modified":"2025-08-22T11:32:44","modified_gmt":"2025-08-22T06:02:44","slug":"shortest-job-first","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/shortest-job-first\/","title":{"rendered":"Shortest Job first (SJF) | Greedy Algorithm"},"content":{"rendered":"\n<p>You are given a list of <strong>CPU burst times<\/strong> for processes that all arrive at time 0. Using <strong>Shortest Job First (SJF), non-preemptive<\/strong>, schedule the processes to minimize the <strong>average waiting time<\/strong>. You need to return the <strong>floor<\/strong> of the average waiting time as per the GFG requirement.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/shortest-job-first\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<p><strong>Example 1<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"Input: bt = [3, 1, 2]\nSJF order: [1, 2, 3]\nWaiting times: [0, 1, 3]\nAverage waiting time = (0 + 1 + 3) \/ 3 = 1.333..., answer = 1\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #DCDCAA\">Input<\/span><span style=\"color: #D4D4D4\">: bt = [3, 1, 2]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">SJF<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">order<\/span><span style=\"color: #D4D4D4\">: [1, 2, 3]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">Waiting<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">times<\/span><span style=\"color: #D4D4D4\">: [0, 1, 3]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Average waiting time = (0 + 1 + 3) \/ 3 = 1.333..., answer = 1<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p><strong>Example 2<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"Input: bt = [5, 5, 5]\nSJF order: [5, 5, 5]\nWaiting times: [0, 5, 10]\nAverage waiting time = (0 + 5 + 10) \/ 3 = 5, answer = 5\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #DCDCAA\">Input<\/span><span style=\"color: #D4D4D4\">: bt = [5, 5, 5]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">SJF<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">order<\/span><span style=\"color: #D4D4D4\">: [5, 5, 5]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">Waiting<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">times<\/span><span style=\"color: #D4D4D4\">: [0, 5, 10]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Average waiting time = (0 + 5 + 10) \/ 3 = 5, answer = 5<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>The challenge is to pick an execution order that results in the smallest possible average waiting time and return its floor.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Intuition and Approach (Optimal Greedy)<\/h2>\n\n\n\n<p>For SJF with all arrivals at time 0, the optimal strategy is simple: <strong>sort the burst times in non-decreasing order<\/strong> and execute in that order. The reason is:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A shorter job placed earlier keeps the cumulative waiting time of all following jobs smaller.<\/li>\n\n\n\n<li>This is a classic exchange argument. If a longer job is before a shorter job, swapping them never increases and usually decreases the total waiting time.<\/li>\n<\/ul>\n\n\n\n<p>Once sorted:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <strong>waiting time<\/strong> of a process equals the <strong>sum of burst times of all previous processes<\/strong>.<\/li>\n\n\n\n<li>Maintain a running prefix sum of burst times to accumulate total waiting time.<\/li>\n\n\n\n<li>Compute <strong>floor(total_waiting_time \/ n)<\/strong> to match GFG output.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Code Implementation<\/h2>\n\n\n\n<p>Your provided optimal greedy solution with minimal comments only:<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def solve(self, bt):\n        # Sort burst times (Greedy: always pick shortest job first)\n        bt.sort()\n        \n        n = len(bt)\n        waiting_time = 0\n        total_waiting_time = 0\n        \n        # Calculate waiting times\n        for i in range(1, n):\n            waiting_time += bt[i-1]   # Add previous process burst time\n            total_waiting_time += waiting_time\n        \n        # Average waiting time\n        avg_waiting_time = total_waiting_time \/\/ n   # floor division as per GFG\n        \n        return avg_waiting_time\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">solve<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">bt<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Sort burst times (Greedy: always pick shortest job first)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        bt.sort()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(bt)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        waiting_time = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        total_waiting_time = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Calculate waiting times<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            waiting_time += bt[i-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">]   <\/span><span style=\"color: #6A9955\"># Add previous process burst time<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            total_waiting_time += waiting_time<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Average waiting time<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        avg_waiting_time = total_waiting_time \/\/ n   <\/span><span style=\"color: #6A9955\"># floor division as per GFG<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> avg_waiting_time<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Code explanation<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Sort burst times<\/strong> so that shorter jobs execute first.<\/li>\n\n\n\n<li>Use a <strong>running prefix sum<\/strong> <code>waiting_time<\/code> that adds the previous job\u2019s burst each step.<\/li>\n\n\n\n<li>Accumulate <code>total_waiting_time<\/code> by adding the current <code>waiting_time<\/code> for each process starting from index 1.<br>The first job waits 0, the second waits <code>bt[0]<\/code>, the third waits <code>bt[0] + bt[1]<\/code>, and so on.<\/li>\n\n\n\n<li>Finally, compute the <strong>floor of the average<\/strong> using integer division <code>\/\/<\/code>.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Time and Space Complexity<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Precise:<\/strong> sorting takes <strong>O(n log n)<\/strong>, the single pass accumulation takes <strong>O(n)<\/strong>, so total <strong>O(n log n + n)<\/strong><\/li>\n\n\n\n<li><strong>Simplified:<\/strong> <strong>O(n log n)<\/strong> time<\/li>\n\n\n\n<li><strong>Space:<\/strong> sorting in place and constant extra variables give <strong>O(1)<\/strong> extra space<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>For <strong>Shortest Job First<\/strong> with all processes available at time 0, sorting the burst times and computing prefix sums yields the <strong>minimum average waiting time<\/strong>. The greedy approach is optimal, easy to implement, and runs in <strong>O(n log n)<\/strong> time with <strong>O(1)<\/strong> extra space.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>You are given a list of CPU burst times for processes that all arrive at time 0. Using Shortest Job First (SJF), non-preemptive, schedule the processes to minimize the average waiting time. You need to return the floor of the average waiting time as per the GFG requirement. Here&#8217;s the [Problem Link] to begin with.<\/p>\n","protected":false},"author":1,"featured_media":975,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[41,19],"class_list":{"0":"post-974","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-intermediate","9":"tag-greedy-algorithm","10":"tag-medium"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/08\/shortest-job-first-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/974","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=974"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/974\/revisions"}],"predecessor-version":[{"id":976,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/974\/revisions\/976"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/975"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=974"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=974"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=974"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}