簡體   English   中英

使用javascript進行“選擇排序”?

[英]“selection sort” using javascript?

如何獲取數組中最小元素的位置,並使用javascript將該值與鄰居值交換為“選擇排序”?

我的HTML是

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script type="text/javascript" src="js/script.js"></script>
    <script src="js/jquery-latest.min.js"></script>
    <link type="text/css" href="style.css" rel="stylesheet" />
</head>

<body>
    <form onsubmit="store(this); return false">
        1:<input type="text" id="one" /><br />
        2:<input type="text" id="two" /><br />
        3:<input type="text" id="three" /><br />
        4:<input type="text" id="four" /><br />
        5:<input type="text" id="five" /><br />
        6:<input type="text" id="six" /><br />
        <input type="button" value="Click Me" onclick="getInput(); output();" />
    </form><br />
    <p id="in">Input</p><br />
    <div id="qstnDiv"></div><br />
    <p id="out">Output</p><br />
    <div id="anwrDiv"></div>

</body>
</html>

我的Javascript是

var list = [];
Math.max.apply(Math,list);//maximum
Math.min.apply(Math,list); //minimum 


function getInput() {
    var str_one = document.getElementById("one").value;
    var str_two = document.getElementById("two").value;
    var str_three = document.getElementById("three").value;
    var str_four = document.getElementById("four").value;
    var str_five = document.getElementById("five").value;
    var str_six = document.getElementById("six").value;
    list.push(str_one,str_two,str_three,str_four,str_five,str_six);
    $('#qstnDiv').html(list+',');
}

function output(){

}

我想使用選擇排序對文本框的數字進行排序,所以請幫助我

有一個特定的功能。

myArray.sort(function(a,b){return b-a});

這是上升的。 如果您更改“ a”和“ b”的順序,則該順序將變得不一致。 如果您需要訪問一個對象,則必須編寫

myArray.sort(function(a,b){return b.propertyName-a.propertyName});

非常明確的選擇排序!

function selectionSort(arr){
    for (let i = 0; i < arr.length; i++){
        let indexOfMin = i // set index of min to the 
        let j = i // set the index to run the while loop for calculating min
        let min = arr[i] // set the initial value of minimum

        // find the minimum from i to end of array
        while (j < arr.length){
            if (arr[j] < min){
                min = arr[j]
                indexOfMin = j
            }
            j++
        }

        if (indexOfMin !== i){ // only swap if the index of minimum and curr item is different
            let tmp = arr[i]
            arr[i] = arr[indexOfMin]
            arr[indexOfMin] = tmp
            console.log(arr)
        }
    }
    return arr
}

sortedList = selectionSort([5,3,4,1,-3,2])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM