2013-10-03 95 views
0

如何獲取數組中最小元素的位置,並使用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(){ 

} 

我要分類編號使用的選擇排序形成的文本框,請幫我

+0

爲什麼需要選擇排序? Javascript已經提供了足夠簡單的'.sort()'函數 – knittl

+0

其實我想要一步一步地完成排序功能,這就是爲什麼......請幫助我找到解決方案。 –

+0

http://en.wikipedia.org/wiki/Selection_sort – bhb

回答

1

有特定功能這個。

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

這是升序。如果您更改「a」和「b」的順序,它將變爲降序。 如果您需要訪問您必須編寫的對象

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