【发布时间】:2019-09-13 03:52:14
【问题描述】:
【问题讨论】:
-
JS 中的字符串还是整数?
-
[10000, 11000, 9000].sort((a, b) => a - b);
标签: javascript sorting integer
【问题讨论】:
[10000, 11000, 9000].sort((a, b) => a - b);
标签: javascript sorting integer
冒泡排序助你一臂之力!!
function bubble_Sort(a)
{
var swapp;
var n = a.length-1;
var x=a;
do {
swapp = false;
for (var i=0; i < n; i++)
{
if (x[i] > x[i+1])
{
var temp = x[i];
x[i] = x[i+1];
x[i+1] = temp;
swapp = true;
}
}
n--;
} while (swapp);
return x;
}
console.log(bubble_sort([10000, 11000, 9000]));
【讨论】:
您可以删除 .toLowerCase() 并将检查包装在 parseInt() 中,它将与您提供的代码一起使用:
<!DOCTYPE html>
<html>
<title>Sort a HTML List Alphabetically</title>
<body>
<p>Click the button to sort the list alphabetically:</p>
<button onclick="sortList()">Sort</button>
<ul id="id01">
<li>10000</li>
<li>11000</li>
<li>9000</li>
<li>12</li>
<li>1</li>
</ul>
<script>
function sortList() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("id01");
switching = true;
/* Make a loop that will continue until
no switching has been done: */
while (switching) {
// start by saying: no switching is done:
switching = false;
b = list.getElementsByTagName("LI");
// Loop through all list-items:
for (i = 0; i < (b.length - 1); i++) {
// start by saying there should be no switching:
shouldSwitch = false;
/* check if the next item should
switch place with the current item: */
if (parseInt(b[i].innerHTML) > parseInt(b[i + 1].innerHTML)) {
/* if next item is alphabetically
lower than current item, mark as a switch
and break the loop: */
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
/* If a switch has been marked, make the switch
and mark the switch as done: */
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
</script>
</body>
</html>
【讨论】:
var a = 0
for(var i = 0; i < numbers; i++){
if(numbers[i] > numbers[i+1]){
a = numbers[i+1];
numbers[i+1] = numbers[i];
numbers[i] = a;
}
}
这称为冒泡排序或插入排序
【讨论】:
你可以使用 Array.prototype.sort 函数:
var test = [3,5,7,2,3,1];
console.log(test.sort());
//result : [1, 2, 3, 3, 5, 7]
//for descending
console.log(test.sort((a,b) => b-a));
//result : [7, 5, 3, 3, 2, 1]
【讨论】:
[1,10,6,5].sort() 并仔细观察结果。对于数字排序(相对于字典排序),您总是需要提供 sortFunc