Skip to content
Snippets Groups Projects

cmsc351_selection_sort

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Diqi Zeng

    CMSC 351 selection sort

    selection_cmsc351.js 759 B
    function selection_sort(A) {
      const n = A.length - 1;
      for (let i = n; i >= 2; i--) {
        let k = 1;
        for (let j = 2; j <= i; j++) {
          console.log(`COMPARE A[j(${j})]->${A[j]} with A[k(${k})]->${A[k]}`);
          if (A[j] > A[k]) {
            k = j;
          }
        }
        console.log(`SWAP A[k(${k})]->${A[k]} with A[i(${i})]->${A[i]}`);
        console.log(A);
        const t = A[k];
        A[k] = A[i];
        A[i] = t;
        console.log(A);
        console.log('---');
      }
    }
    
    // Insert NULL at index 0 because CMSC 351 code INDEX stars from 1
    const arr = [null, 64, 25, 12, 22, 11];
    selection_sort(arr);
    console.log(arr);
    
    // RIGHT SIDE IS SORTED PART
    // [64, 25, 12, 22, 11|]
    // [11, 25, 12, 22, |64]
    // [11, 22, 12, |25, 64]
    // [11, 12, |22, 25, 64]
    // [11, |12, 22, 25, 64]
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment