{"id":6175,"date":"2025-05-29T18:58:14","date_gmt":"2025-05-29T13:28:14","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=6175"},"modified":"2025-06-09T10:05:02","modified_gmt":"2025-06-09T04:35:02","slug":"selection-sort","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/selection-sort\/","title":{"rendered":"Selection Sort"},"content":{"rendered":"\n<!-- Prism.js CSS and JS -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.css\" rel=\"stylesheet\" \/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n.wp_blog_code-tabs-container {\n    font-family: \"Segoe UI\", sans-serif !important;\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    border: 1px solid #ddd !important;\n    border-radius: 8px !important;\n    overflow: hidden !important;\n    background-color: white !important;\n}\n\n.wp_blog_code-tabs-header {\n    background: #f7f7f7 !important;\n    display: flex !important;\n    border-bottom: 1px solid #ddd !important;\n}\n\n.wp_blog_code-tab-button {\n    flex: 1 !important;\n    padding: 10px 15px !important;\n    border: none !important;\n    background: transparent !important;\n    cursor: pointer !important;\n    font-weight: bold !important;\n    transition: background 0.2s !important;\n    color: #242B33 !important;\n}\n\n.wp_blog_code-tab-button.active {\n    background: white !important;\n    border-bottom: 3px solid #0073aa !important;\n}\n\n.wp_blog_code-tab-content {\n    display: none !important;\n    padding: 20px !important;\n    background: #242B33 !important;\n}\n\n.wp_blog_code-tab-content > pre {\n    background: #242B33 !important;\n}\n\n.wp_blog_code-tab-content.active {\n    display: block !important;\n}\n\n.wp_blog_code-tab-content pre {\n    margin: 0 !important;\n    overflow-x: auto !important;\n}\n\n.wp_blog_explanation {\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    font-family: \"Segoe UI\", sans-serif !important;\n    line-height: 1.6 !important;\n    background: white !important;\n    color: black !important;\n    padding: 1rem !important;\n    border-radius: 8px !important;\n}\n\n.wp_blog_explanation h2 {\n    color: #0073aa !important;\n    font-size: 1.5rem !important;\n    margin-bottom: 0.5rem !important;\n}\n\n.wp_blog_explanation code {\n    background: #f1f1f1 !important;\n    padding: 2px 6px !important;\n    border-radius: 4px !important;\n    font-family: monospace !important;\n}\n\n.wp_blog_explanation h1,\n.wp_blog_explanation h2,\n.wp_blog_explanation h3,\n.wp_blog_explanation h4,\n.wp_blog_explanation h5,\n.wp_blog_explanation h6,\n.wp_blog_explanation p {\n    margin-top: 10px !important;\n    margin-bottom: 10px !important;\n}\n<\/style>\n\n<!-- \u2705 START: Blog Explanation -->\n\n\n<div class=\"wp_blog_explanation\">\n    <p>\n      Selection Sort is a simple comparison-based sorting algorithm. It divides the array into two parts: a sorted subarray and an unsorted subarray. Initially, the sorted part is empty, and the unsorted part is the entire array. In each iteration, it finds the minimum element from the unsorted part and moves it to the end of the sorted part.\n    <\/p>\n    <h2>Example:<\/h2>\n    <p>For input <code>[4, 5, 1, 3, 9]<\/code>, the sorted output will be <code>[1, 3, 4, 5, 9]<\/code>.<\/p>\n   \n    <h2>Approach:<\/h2>\n    <ul>\n      <li>Iterate over the array from index 0 to n-2.<\/li>\n      <li>For each index <code>i<\/code>, assume the element at <code>i<\/code> is the minimum in the unsorted part.<\/li>\n      <li>Run an inner loop from <code>j = i+1<\/code> to <code>n-1<\/code> to find the actual minimum element.<\/li>\n      <li>If a smaller element is found, update the min index.<\/li>\n      <li>After the inner loop, swap the element at <code>i<\/code> with the element at <code>min<\/code> (if they\u2019re not the same).<\/li>\n      <li>Repeat until the array is sorted.<\/li>\n    <\/ul>\n\n    <h2>Dry Run (Example: [4, 5, 1, 3, 9])<\/h2>\n    <ul>\n      <li>Start from index 0 \u2192 Find the smallest element \u2192 it&#8217;s 1. Swap with 4 \u2192 [1, 5, 4, 3, 9]<\/li>\n      <li>Index 1 \u2192 Smallest from index 1 \u2192 3. Swap with 5 \u2192 [1, 3, 4, 5, 9]<\/li>\n      <li>Index 2 \u2192 Smallest is 4 \u2192 already in place \u2192 [1, 3, 4, 5, 9]<\/li>\n      <li>Index 3 \u2192 Smallest is 5 \u2192 already in place \u2192 [1, 3, 4, 5, 9]<\/li>\n    <\/ul>\n\n    <h2>Time Complexity (TC):<\/h2>\n    <ul>\n      <li>O(n\u00b2) in all cases \u2014 best, average, and worst.<\/li>\n      <li>Roughly n*(n-1)\/2 comparisons are always performed.<\/li>\n    <\/ul>\n  \n    <h2>Space Complexity (TC):<\/h2>\n    <p> O(1)<\/p>\n    <p>Selection Sort is an in-place sorting algorithm, so it doesn&#8217;t require extra space.<\/p>\n  <\/div>\n  \n\n  <div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n      <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">\n  let arr = [4, 5, 1, 3, 9];\n  \n  function selectionSort(arr) {\n    let n = arr.length;\n    for (let i = 0; i < n - 1; i++) {\n      let min = i;\n      for (let j = i + 1; j < n; j++) {\n        if (arr[j] < arr[min]) {\n          min = j;\n        }\n      }\n      if (min != i) {\n        let temp = arr[i];\n        arr[i] = arr[min];\n        arr[min] = temp;\n      }\n    }\n    return arr;\n  }\n  \n  let result = selectionSort(arr);\n  console.log(\"Sorted array\", result);\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre><code class=\"language-cpp\">\n  #include &lt;iostream&gt;\n  using namespace std;\n  \n  void selectionSort(int arr[], int n) {\n    for (int i = 0; i < n - 1; i++) {\n      int min = i;\n      for (int j = i + 1; j < n; j++) {\n        if (arr[j] < arr[min]) {\n          min = j;\n        }\n      }\n      if (min != i) {\n        int temp = arr[i];\n        arr[i] = arr[min];\n        arr[min] = temp;\n      }\n    }\n  }\n  \n  int main() {\n    int arr[] = {4, 5, 1, 3, 9};\n    int n = sizeof(arr) \/ sizeof(arr[0]);\n    selectionSort(arr, n);\n    for (int i = 0; i < n; i++) {\n      cout << arr[i] << \" \";\n    }\n    return 0;\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n      <pre><code class=\"language-c\">\n  #include &lt;stdio.h&gt;\n  \n  void selectionSort(int arr[], int n) {\n    for (int i = 0; i < n - 1; i++) {\n      int min = i;\n      for (int j = i + 1; j < n; j++) {\n        if (arr[j] < arr[min]) {\n          min = j;\n        }\n      }\n      if (min != i) {\n        int temp = arr[i];\n        arr[i] = arr[min];\n        arr[min] = temp;\n      }\n    }\n  }\n  \n  int main() {\n    int arr[] = {4, 5, 1, 3, 9};\n    int n = sizeof(arr) \/ sizeof(arr[0]);\n    selectionSort(arr, n);\n    for (int i = 0; i < n; i++) {\n      printf(\"%d \", arr[i]);\n    }\n    return 0;\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">\n  public class Main {\n    public static void selectionSort(int[] arr) {\n      int n = arr.length;\n      for (int i = 0; i < n - 1; i++) {\n        int min = i;\n        for (int j = i + 1; j < n; j++) {\n          if (arr[j] < arr[min]) {\n            min = j;\n          }\n        }\n        if (min != i) {\n          int temp = arr[i];\n          arr[i] = arr[min];\n          arr[min] = temp;\n        }\n      }\n    }\n  \n    public static void main(String[] args) {\n      int[] arr = {4, 5, 1, 3, 9};\n      selectionSort(arr);\n      for (int num : arr) {\n        System.out.print(num + \" \");\n      }\n    }\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">\n  def selectionSort(arr):\n      n = len(arr)\n      for i in range(n - 1):\n          min_idx = i\n          for j in range(i + 1, n):\n              if arr[j] < arr[min_idx]:\n                  min_idx = j\n          if min_idx != i:\n              arr[i], arr[min_idx] = arr[min_idx], arr[i]\n      return arr\n  \n  arr = [4, 5, 1, 3, 9]\n  print(\"Sorted array\", selectionSort(arr))\n      <\/code><\/pre>\n    <\/div>\n  <\/div>\n  \n  \n  \n  \n<!-- \u2705 JS Tab Switch Logic -->\n<script>\ndocument.addEventListener('DOMContentLoaded', function () {\n    const buttons = document.querySelectorAll('.wp_blog_code-tab-button');\n    const contents = document.querySelectorAll('.wp_blog_code-tab-content');\n    buttons.forEach(button => {\n        button.addEventListener('click', () => {\n            const lang = button.getAttribute('data-lang');\n            buttons.forEach(btn => btn.classList.remove('active'));\n            button.classList.add('active');\n            contents.forEach(content => {\n                content.classList.toggle('active', content.getAttribute('data-lang') === lang);\n            });\n        });\n    });\n});\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>Selection Sort is a simple comparison-based sorting algorithm. It divides the array into two parts: a sorted subarray and an unsorted subarray. Initially, the sorted part is empty, and the unsorted part is the entire array. In each iteration, it finds the minimum element from the unsorted part and moves it to the end of<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[811,810],"tags":[],"class_list":{"0":"post-6175","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-data-structures-and-algorithms","7":"category-dsa"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6175","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=6175"}],"version-history":[{"count":3,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6175\/revisions"}],"predecessor-version":[{"id":6563,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6175\/revisions\/6563"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=6175"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=6175"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=6175"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}