Selection Sort Algorithm (Node.js)Merge Sort ProgramSorting an int[] array using insertion sort algorithm -...

As a girl, how can I voice male characters effectively?

Find the number for the question mark

The locus of polynomials with specified root multiplicities

Is there a difference between historical fiction and creative non-fiction?

Does SQL Server's serializable isolation level lock entire table

What kind of nut is this

What is the origin of the minced oath “Jiminy”?

I'm made of obsolete parts

How to know the size of a package

Minimum perfect squares needed to sum up to a target

Should I reveal productivity tricks to peers, or keep them to myself in order to be more productive than the others?

Had there been instances of national states banning harmful imports before the Opium wars?

What are the most important factors in determining how fast technology progresses?

Is there any way to ward an area against Sending?

How to catch creatures that can predict the next few minutes?

Is there any problem with students seeing faculty naked in university gym?

What are the limits on an impeached and not convicted president?

Selection Sort Algorithm (Node.js)

Can't change the screenshot directory because "com.apple.screencapture: command not found"

This fell out of my toilet when I unscrewed the supply line. What is it?

The work of mathematicians outside their professional environment

In what sense is SL(2,q) "very far from abelian"?

What should I do if I find a mistake in my submitted master's thesis?

Why is the time of useful consciousness only seconds at high altitudes, when I can hold my breath much longer at ground level?



Selection Sort Algorithm (Node.js)


Merge Sort ProgramSorting an int[] array using insertion sort algorithm - follow-upBuilding an efficient bubble sort functionAsc and desc array sort methodsSort array of objects with hierarchy by hierarchy and nameRadix sort implementation in JS (LSD)Generic Merge Sort in C++Quicksort with Insertion Sort and Improved Pivot SelectionSorting Algorithms (Python)Shell Sort, Insertion Sort, Bubble Sort, Selection Sort Algorithms (Python)






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}








1












$begingroup$


I wanted to implement a selection sort and wanted to make sure that I'm doing it correctly. I wanted to do it in a way that's efficient and use recursion. Please let me know if I am doing this correctly or if there is a better way for me to do it.



     /**
* selectionSort
* @param toSort
* @param sorted
* @returns {Array}
*/
function selectionSort(toSort, sorted=[]) {
if (!toSort.length) {
return sorted;
}
let minIndex = findMinimum(toSort);
sorted.push(...toSort.splice(minIndex, 1))
return selectionSort(toSort, sorted);
}

function findMinimum(arr) {
let minIndex=0;
arr.forEach(function (item, index) {
if(item < arr[minIndex]) {
minIndex = index;
}
})
return minIndex;
}


const testCase = [64, 25, 12, 22, 11]
const answer = selectionSort(testCase);










share|improve this question









New contributor



Christopher Chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$














  • $begingroup$
    Is this code using node.js?
    $endgroup$
    – dfhwze
    7 hours ago






  • 1




    $begingroup$
    Why use recursion when a loop would do just fine? Recursion is just going to have a lot of stack buildup for large arrays and extra function calls.
    $endgroup$
    – jfriend00
    7 hours ago












  • $begingroup$
    A for loop is generally more efficient than .forEach() as there's no function call and new scope involved. Probably best to use for/of.
    $endgroup$
    – jfriend00
    7 hours ago












  • $begingroup$
    @jfriend00 I'm trying to familiarize myself with recursion more. I didn't know that it's better to use loops in some cases. Thanks for the tip with the for/of also
    $endgroup$
    – Christopher Chen
    2 hours ago




















1












$begingroup$


I wanted to implement a selection sort and wanted to make sure that I'm doing it correctly. I wanted to do it in a way that's efficient and use recursion. Please let me know if I am doing this correctly or if there is a better way for me to do it.



     /**
* selectionSort
* @param toSort
* @param sorted
* @returns {Array}
*/
function selectionSort(toSort, sorted=[]) {
if (!toSort.length) {
return sorted;
}
let minIndex = findMinimum(toSort);
sorted.push(...toSort.splice(minIndex, 1))
return selectionSort(toSort, sorted);
}

function findMinimum(arr) {
let minIndex=0;
arr.forEach(function (item, index) {
if(item < arr[minIndex]) {
minIndex = index;
}
})
return minIndex;
}


const testCase = [64, 25, 12, 22, 11]
const answer = selectionSort(testCase);










share|improve this question









New contributor



Christopher Chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$














  • $begingroup$
    Is this code using node.js?
    $endgroup$
    – dfhwze
    7 hours ago






  • 1




    $begingroup$
    Why use recursion when a loop would do just fine? Recursion is just going to have a lot of stack buildup for large arrays and extra function calls.
    $endgroup$
    – jfriend00
    7 hours ago












  • $begingroup$
    A for loop is generally more efficient than .forEach() as there's no function call and new scope involved. Probably best to use for/of.
    $endgroup$
    – jfriend00
    7 hours ago












  • $begingroup$
    @jfriend00 I'm trying to familiarize myself with recursion more. I didn't know that it's better to use loops in some cases. Thanks for the tip with the for/of also
    $endgroup$
    – Christopher Chen
    2 hours ago
















1












1








1





$begingroup$


I wanted to implement a selection sort and wanted to make sure that I'm doing it correctly. I wanted to do it in a way that's efficient and use recursion. Please let me know if I am doing this correctly or if there is a better way for me to do it.



     /**
* selectionSort
* @param toSort
* @param sorted
* @returns {Array}
*/
function selectionSort(toSort, sorted=[]) {
if (!toSort.length) {
return sorted;
}
let minIndex = findMinimum(toSort);
sorted.push(...toSort.splice(minIndex, 1))
return selectionSort(toSort, sorted);
}

function findMinimum(arr) {
let minIndex=0;
arr.forEach(function (item, index) {
if(item < arr[minIndex]) {
minIndex = index;
}
})
return minIndex;
}


const testCase = [64, 25, 12, 22, 11]
const answer = selectionSort(testCase);










share|improve this question









New contributor



Christopher Chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$




I wanted to implement a selection sort and wanted to make sure that I'm doing it correctly. I wanted to do it in a way that's efficient and use recursion. Please let me know if I am doing this correctly or if there is a better way for me to do it.



     /**
* selectionSort
* @param toSort
* @param sorted
* @returns {Array}
*/
function selectionSort(toSort, sorted=[]) {
if (!toSort.length) {
return sorted;
}
let minIndex = findMinimum(toSort);
sorted.push(...toSort.splice(minIndex, 1))
return selectionSort(toSort, sorted);
}

function findMinimum(arr) {
let minIndex=0;
arr.forEach(function (item, index) {
if(item < arr[minIndex]) {
minIndex = index;
}
})
return minIndex;
}


const testCase = [64, 25, 12, 22, 11]
const answer = selectionSort(testCase);







javascript algorithm sorting recursion node.js






share|improve this question









New contributor



Christopher Chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|improve this question









New contributor



Christopher Chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|improve this question




share|improve this question








edited 4 hours ago









AlexV

4,4732 gold badges11 silver badges36 bronze badges




4,4732 gold badges11 silver badges36 bronze badges






New contributor



Christopher Chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked 8 hours ago









Christopher ChenChristopher Chen

112 bronze badges




112 bronze badges




New contributor



Christopher Chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




Christopher Chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

















  • $begingroup$
    Is this code using node.js?
    $endgroup$
    – dfhwze
    7 hours ago






  • 1




    $begingroup$
    Why use recursion when a loop would do just fine? Recursion is just going to have a lot of stack buildup for large arrays and extra function calls.
    $endgroup$
    – jfriend00
    7 hours ago












  • $begingroup$
    A for loop is generally more efficient than .forEach() as there's no function call and new scope involved. Probably best to use for/of.
    $endgroup$
    – jfriend00
    7 hours ago












  • $begingroup$
    @jfriend00 I'm trying to familiarize myself with recursion more. I didn't know that it's better to use loops in some cases. Thanks for the tip with the for/of also
    $endgroup$
    – Christopher Chen
    2 hours ago




















  • $begingroup$
    Is this code using node.js?
    $endgroup$
    – dfhwze
    7 hours ago






  • 1




    $begingroup$
    Why use recursion when a loop would do just fine? Recursion is just going to have a lot of stack buildup for large arrays and extra function calls.
    $endgroup$
    – jfriend00
    7 hours ago












  • $begingroup$
    A for loop is generally more efficient than .forEach() as there's no function call and new scope involved. Probably best to use for/of.
    $endgroup$
    – jfriend00
    7 hours ago












  • $begingroup$
    @jfriend00 I'm trying to familiarize myself with recursion more. I didn't know that it's better to use loops in some cases. Thanks for the tip with the for/of also
    $endgroup$
    – Christopher Chen
    2 hours ago


















$begingroup$
Is this code using node.js?
$endgroup$
– dfhwze
7 hours ago




$begingroup$
Is this code using node.js?
$endgroup$
– dfhwze
7 hours ago




1




1




$begingroup$
Why use recursion when a loop would do just fine? Recursion is just going to have a lot of stack buildup for large arrays and extra function calls.
$endgroup$
– jfriend00
7 hours ago






$begingroup$
Why use recursion when a loop would do just fine? Recursion is just going to have a lot of stack buildup for large arrays and extra function calls.
$endgroup$
– jfriend00
7 hours ago














$begingroup$
A for loop is generally more efficient than .forEach() as there's no function call and new scope involved. Probably best to use for/of.
$endgroup$
– jfriend00
7 hours ago






$begingroup$
A for loop is generally more efficient than .forEach() as there's no function call and new scope involved. Probably best to use for/of.
$endgroup$
– jfriend00
7 hours ago














$begingroup$
@jfriend00 I'm trying to familiarize myself with recursion more. I didn't know that it's better to use loops in some cases. Thanks for the tip with the for/of also
$endgroup$
– Christopher Chen
2 hours ago






$begingroup$
@jfriend00 I'm trying to familiarize myself with recursion more. I didn't know that it's better to use loops in some cases. Thanks for the tip with the for/of also
$endgroup$
– Christopher Chen
2 hours ago












2 Answers
2






active

oldest

votes


















2














$begingroup$

I'd suggest the following changes:




  1. Use a loop instead of recursion

  2. Use for/of instead of .forEach()

  3. push a single value instead of using an array with one element in it

  4. cache the lowest value so far so you don't have to constantly refetch it on every comparison

  5. Use a temporary array for the sort so the function is non-destructive to the source array (consistent with most array methods)

  6. Use const where you can.


Code:



 /**
* selectionSort
* @param toSort (not modified)
* @param sorted (new sorted array)
* @returns {Array}
*/
function selectionSort(toSort, sorted = []) {
if (!toSort.length) {
return sorted;
}
// make copy so we don't modify source
const sortData = toSort.slice();

while (sortData.length) {
const minIndex = findMinimum(sortData);
sorted.push(sortData[minIndex]);
// remove min item from data left to be sorted
sortData.splice(minIndex, 1);
}
return sorted;
}

function findMinimum(arr) {
let minIndex = 0, minValue = arr[0];
for (const [index, item] of arr.entries()) {
if (item < minValue) {
minIndex = index;
minValue = item;
}
}
return minIndex;
}


const testCase = [64, 25, 12, 22, 11]
const answer = selectionSort(testCase);
console.log(answer);





share|improve this answer











$endgroup$























    1














    $begingroup$

    Review





    • findMinimum means to me that you find the minimum value in an array of items. Since your function returns the index instead, call it indexOfMinimum.

    • Prefer the use of const over let if you only assign a variable once: let minIndex = findMinimum(toSort); -> const minIndex = findMinimum(toSort);.

    • Use arrow notation to write more compact functions: function (item, index) -> (item, index) =>.

    • Your documentation seems like waisted space. If you document a public function (which is a good thing), put in some effort to write a clear description of the function, not just the name of the method copied.

    • Use whitespace to write more idiomatic javascript:



      • let minIndex=0; -> let minIndex = 0;


      • if(item < arr[minIndex]) -> if (item < arr[minIndex])




    Rewritten:



    function selectionSort(toSort, sorted=[]) {
    if (!toSort.length) {
    return sorted;
    }
    const minIndex = indexOfMinimum(toSort);
    sorted.push(...toSort.splice(minIndex, 1))
    return selectionSort(toSort, sorted);
    }

    function indexOfMinimum(arr) {
    let minIndex = 0;
    arr.forEach((item, index) => {
    if (item < arr[minIndex]) {
    minIndex = index;
    }
    })
    return minIndex;
    }





    share|improve this answer











    $endgroup$















    • $begingroup$
      Those are good suggestions. Thank you. What do you mean by more idiomatic javascript?
      $endgroup$
      – Christopher Chen
      2 hours ago













    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });







    Christopher Chen is a new contributor. Be nice, and check out our Code of Conduct.










    draft saved

    draft discarded
















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f229865%2fselection-sort-algorithm-node-js%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    $begingroup$

    I'd suggest the following changes:




    1. Use a loop instead of recursion

    2. Use for/of instead of .forEach()

    3. push a single value instead of using an array with one element in it

    4. cache the lowest value so far so you don't have to constantly refetch it on every comparison

    5. Use a temporary array for the sort so the function is non-destructive to the source array (consistent with most array methods)

    6. Use const where you can.


    Code:



     /**
    * selectionSort
    * @param toSort (not modified)
    * @param sorted (new sorted array)
    * @returns {Array}
    */
    function selectionSort(toSort, sorted = []) {
    if (!toSort.length) {
    return sorted;
    }
    // make copy so we don't modify source
    const sortData = toSort.slice();

    while (sortData.length) {
    const minIndex = findMinimum(sortData);
    sorted.push(sortData[minIndex]);
    // remove min item from data left to be sorted
    sortData.splice(minIndex, 1);
    }
    return sorted;
    }

    function findMinimum(arr) {
    let minIndex = 0, minValue = arr[0];
    for (const [index, item] of arr.entries()) {
    if (item < minValue) {
    minIndex = index;
    minValue = item;
    }
    }
    return minIndex;
    }


    const testCase = [64, 25, 12, 22, 11]
    const answer = selectionSort(testCase);
    console.log(answer);





    share|improve this answer











    $endgroup$




















      2














      $begingroup$

      I'd suggest the following changes:




      1. Use a loop instead of recursion

      2. Use for/of instead of .forEach()

      3. push a single value instead of using an array with one element in it

      4. cache the lowest value so far so you don't have to constantly refetch it on every comparison

      5. Use a temporary array for the sort so the function is non-destructive to the source array (consistent with most array methods)

      6. Use const where you can.


      Code:



       /**
      * selectionSort
      * @param toSort (not modified)
      * @param sorted (new sorted array)
      * @returns {Array}
      */
      function selectionSort(toSort, sorted = []) {
      if (!toSort.length) {
      return sorted;
      }
      // make copy so we don't modify source
      const sortData = toSort.slice();

      while (sortData.length) {
      const minIndex = findMinimum(sortData);
      sorted.push(sortData[minIndex]);
      // remove min item from data left to be sorted
      sortData.splice(minIndex, 1);
      }
      return sorted;
      }

      function findMinimum(arr) {
      let minIndex = 0, minValue = arr[0];
      for (const [index, item] of arr.entries()) {
      if (item < minValue) {
      minIndex = index;
      minValue = item;
      }
      }
      return minIndex;
      }


      const testCase = [64, 25, 12, 22, 11]
      const answer = selectionSort(testCase);
      console.log(answer);





      share|improve this answer











      $endgroup$


















        2














        2










        2







        $begingroup$

        I'd suggest the following changes:




        1. Use a loop instead of recursion

        2. Use for/of instead of .forEach()

        3. push a single value instead of using an array with one element in it

        4. cache the lowest value so far so you don't have to constantly refetch it on every comparison

        5. Use a temporary array for the sort so the function is non-destructive to the source array (consistent with most array methods)

        6. Use const where you can.


        Code:



         /**
        * selectionSort
        * @param toSort (not modified)
        * @param sorted (new sorted array)
        * @returns {Array}
        */
        function selectionSort(toSort, sorted = []) {
        if (!toSort.length) {
        return sorted;
        }
        // make copy so we don't modify source
        const sortData = toSort.slice();

        while (sortData.length) {
        const minIndex = findMinimum(sortData);
        sorted.push(sortData[minIndex]);
        // remove min item from data left to be sorted
        sortData.splice(minIndex, 1);
        }
        return sorted;
        }

        function findMinimum(arr) {
        let minIndex = 0, minValue = arr[0];
        for (const [index, item] of arr.entries()) {
        if (item < minValue) {
        minIndex = index;
        minValue = item;
        }
        }
        return minIndex;
        }


        const testCase = [64, 25, 12, 22, 11]
        const answer = selectionSort(testCase);
        console.log(answer);





        share|improve this answer











        $endgroup$



        I'd suggest the following changes:




        1. Use a loop instead of recursion

        2. Use for/of instead of .forEach()

        3. push a single value instead of using an array with one element in it

        4. cache the lowest value so far so you don't have to constantly refetch it on every comparison

        5. Use a temporary array for the sort so the function is non-destructive to the source array (consistent with most array methods)

        6. Use const where you can.


        Code:



         /**
        * selectionSort
        * @param toSort (not modified)
        * @param sorted (new sorted array)
        * @returns {Array}
        */
        function selectionSort(toSort, sorted = []) {
        if (!toSort.length) {
        return sorted;
        }
        // make copy so we don't modify source
        const sortData = toSort.slice();

        while (sortData.length) {
        const minIndex = findMinimum(sortData);
        sorted.push(sortData[minIndex]);
        // remove min item from data left to be sorted
        sortData.splice(minIndex, 1);
        }
        return sorted;
        }

        function findMinimum(arr) {
        let minIndex = 0, minValue = arr[0];
        for (const [index, item] of arr.entries()) {
        if (item < minValue) {
        minIndex = index;
        minValue = item;
        }
        }
        return minIndex;
        }


        const testCase = [64, 25, 12, 22, 11]
        const answer = selectionSort(testCase);
        console.log(answer);






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 4 hours ago

























        answered 6 hours ago









        jfriend00jfriend00

        3,4829 silver badges18 bronze badges




        3,4829 silver badges18 bronze badges




























            1














            $begingroup$

            Review





            • findMinimum means to me that you find the minimum value in an array of items. Since your function returns the index instead, call it indexOfMinimum.

            • Prefer the use of const over let if you only assign a variable once: let minIndex = findMinimum(toSort); -> const minIndex = findMinimum(toSort);.

            • Use arrow notation to write more compact functions: function (item, index) -> (item, index) =>.

            • Your documentation seems like waisted space. If you document a public function (which is a good thing), put in some effort to write a clear description of the function, not just the name of the method copied.

            • Use whitespace to write more idiomatic javascript:



              • let minIndex=0; -> let minIndex = 0;


              • if(item < arr[minIndex]) -> if (item < arr[minIndex])




            Rewritten:



            function selectionSort(toSort, sorted=[]) {
            if (!toSort.length) {
            return sorted;
            }
            const minIndex = indexOfMinimum(toSort);
            sorted.push(...toSort.splice(minIndex, 1))
            return selectionSort(toSort, sorted);
            }

            function indexOfMinimum(arr) {
            let minIndex = 0;
            arr.forEach((item, index) => {
            if (item < arr[minIndex]) {
            minIndex = index;
            }
            })
            return minIndex;
            }





            share|improve this answer











            $endgroup$















            • $begingroup$
              Those are good suggestions. Thank you. What do you mean by more idiomatic javascript?
              $endgroup$
              – Christopher Chen
              2 hours ago
















            1














            $begingroup$

            Review





            • findMinimum means to me that you find the minimum value in an array of items. Since your function returns the index instead, call it indexOfMinimum.

            • Prefer the use of const over let if you only assign a variable once: let minIndex = findMinimum(toSort); -> const minIndex = findMinimum(toSort);.

            • Use arrow notation to write more compact functions: function (item, index) -> (item, index) =>.

            • Your documentation seems like waisted space. If you document a public function (which is a good thing), put in some effort to write a clear description of the function, not just the name of the method copied.

            • Use whitespace to write more idiomatic javascript:



              • let minIndex=0; -> let minIndex = 0;


              • if(item < arr[minIndex]) -> if (item < arr[minIndex])




            Rewritten:



            function selectionSort(toSort, sorted=[]) {
            if (!toSort.length) {
            return sorted;
            }
            const minIndex = indexOfMinimum(toSort);
            sorted.push(...toSort.splice(minIndex, 1))
            return selectionSort(toSort, sorted);
            }

            function indexOfMinimum(arr) {
            let minIndex = 0;
            arr.forEach((item, index) => {
            if (item < arr[minIndex]) {
            minIndex = index;
            }
            })
            return minIndex;
            }





            share|improve this answer











            $endgroup$















            • $begingroup$
              Those are good suggestions. Thank you. What do you mean by more idiomatic javascript?
              $endgroup$
              – Christopher Chen
              2 hours ago














            1














            1










            1







            $begingroup$

            Review





            • findMinimum means to me that you find the minimum value in an array of items. Since your function returns the index instead, call it indexOfMinimum.

            • Prefer the use of const over let if you only assign a variable once: let minIndex = findMinimum(toSort); -> const minIndex = findMinimum(toSort);.

            • Use arrow notation to write more compact functions: function (item, index) -> (item, index) =>.

            • Your documentation seems like waisted space. If you document a public function (which is a good thing), put in some effort to write a clear description of the function, not just the name of the method copied.

            • Use whitespace to write more idiomatic javascript:



              • let minIndex=0; -> let minIndex = 0;


              • if(item < arr[minIndex]) -> if (item < arr[minIndex])




            Rewritten:



            function selectionSort(toSort, sorted=[]) {
            if (!toSort.length) {
            return sorted;
            }
            const minIndex = indexOfMinimum(toSort);
            sorted.push(...toSort.splice(minIndex, 1))
            return selectionSort(toSort, sorted);
            }

            function indexOfMinimum(arr) {
            let minIndex = 0;
            arr.forEach((item, index) => {
            if (item < arr[minIndex]) {
            minIndex = index;
            }
            })
            return minIndex;
            }





            share|improve this answer











            $endgroup$



            Review





            • findMinimum means to me that you find the minimum value in an array of items. Since your function returns the index instead, call it indexOfMinimum.

            • Prefer the use of const over let if you only assign a variable once: let minIndex = findMinimum(toSort); -> const minIndex = findMinimum(toSort);.

            • Use arrow notation to write more compact functions: function (item, index) -> (item, index) =>.

            • Your documentation seems like waisted space. If you document a public function (which is a good thing), put in some effort to write a clear description of the function, not just the name of the method copied.

            • Use whitespace to write more idiomatic javascript:



              • let minIndex=0; -> let minIndex = 0;


              • if(item < arr[minIndex]) -> if (item < arr[minIndex])




            Rewritten:



            function selectionSort(toSort, sorted=[]) {
            if (!toSort.length) {
            return sorted;
            }
            const minIndex = indexOfMinimum(toSort);
            sorted.push(...toSort.splice(minIndex, 1))
            return selectionSort(toSort, sorted);
            }

            function indexOfMinimum(arr) {
            let minIndex = 0;
            arr.forEach((item, index) => {
            if (item < arr[minIndex]) {
            minIndex = index;
            }
            })
            return minIndex;
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 7 hours ago

























            answered 7 hours ago









            dfhwzedfhwze

            13.1k3 gold badges22 silver badges92 bronze badges




            13.1k3 gold badges22 silver badges92 bronze badges















            • $begingroup$
              Those are good suggestions. Thank you. What do you mean by more idiomatic javascript?
              $endgroup$
              – Christopher Chen
              2 hours ago


















            • $begingroup$
              Those are good suggestions. Thank you. What do you mean by more idiomatic javascript?
              $endgroup$
              – Christopher Chen
              2 hours ago
















            $begingroup$
            Those are good suggestions. Thank you. What do you mean by more idiomatic javascript?
            $endgroup$
            – Christopher Chen
            2 hours ago




            $begingroup$
            Those are good suggestions. Thank you. What do you mean by more idiomatic javascript?
            $endgroup$
            – Christopher Chen
            2 hours ago











            Christopher Chen is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded

















            Christopher Chen is a new contributor. Be nice, and check out our Code of Conduct.













            Christopher Chen is a new contributor. Be nice, and check out our Code of Conduct.












            Christopher Chen is a new contributor. Be nice, and check out our Code of Conduct.
















            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f229865%2fselection-sort-algorithm-node-js%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

            Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

            Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...