使用For循环对包含数字的数组进行排序

时间:2016-07-12 14:03:04

标签: javascript arrays sorting

我是Javascript的新手,我有一个包含数字的数组。

 var arr = [2,4,8,1,5,9,3,7,6];

如何在javascript中使用原生For循环对其进行排序。 我知道排序功能可用,但我想通过循环。

输出应该是 -

 var res = [1,2,3,4,5,6,7,8,9];

4 个答案:

答案 0 :(得分:5)



var Arr = [1, 7, 2, 8, 3, 4, 5, 0, 9];

for (var i = 1; i < Arr.length; i++)
    for (var j = 0; j < i; j++)
        if (Arr[i] < Arr[j]) {
          var x = Arr[i];
          Arr[i] = Arr[j];
          Arr[j] = x;
        }

console.log(Arr);
&#13;
&#13;
&#13;

答案 1 :(得分:4)

我会做那样的事......

var input = [2,3,8,1,4,5,9,7,6];

var output = [];
var inserted;

for (var i = 0, ii = input.length ; i < ii ; i++){
  inserted = false;
  for (var j = 0, jj = output.length ; j < jj ; j++){
    if (input[i] < output[j]){
      inserted = true;
      output.splice(j, 0, input[i]);
      break;
    }
  }
  
  if (!inserted)
    output.push(input[i])
}

console.log(output);

也许有更有效的方法,但如果你想使用for循环,这是我的第一个想法...希望它有所帮助

答案 2 :(得分:1)

首先创建一个空数组,排序后的数字将被推入其中。

let sorted = [];

其次,创建一个数组中没有一个数字可以匹配的非常大的数字,这个数字将用于第一次比较以确定数组中哪个数字较小。

let comparison = 9000000000;

创建一个 for 循环。 这个循环里面会有另一个循环,内循环会检查给定数组中的最小数字,一旦得到最小数字,它就会被推入我们创建的空数组中,最小的数字也将被删除从初始数组然后数组将再次运行

``for(a = 0; a < arr.length; a++){

 //This inner loop fetches the smallest number.
 for(b = 0; b < arr.length; a++){
      if(comparison > arr[b]){
           comparison = arr[b];
      }
 }


 //The smallest number is assigned to comparison
 //Now it being pushed to the empty array
 sorted.push(comparison);

 //remove the smallest number from the initial array

 let indexOfSmallNumber = arr.indexOf(comparison);
 arr.splice(indexOfSmallNumber, 1);

 //set the comparison back to 9000000000;
 comparison = 90000000000;

 a = -1;
 // here, "a" is our main  loop index counter and we are setting it to -1 because we don't want it to change to 2 by default, doing this will make the loop run forever until the initial array is empty.

}``

答案 3 :(得分:0)

在W3schools.com的JavaScript数组排序部分下,它讨论了如何将数组中的值与其他数组进行比较,然后根据返回的值对它们进行排序。我更新了代码,以使用for循环对值进行排序。

//Ascending points
var points = [5.0, 3.7, 1.0, 2.9, 3.4, 4.5];
var output = [];
var i;
for (i = 0; i < points.length; i++) {
	points.sort(function (a, b) {
		return a - b
	});
	output += points[i] + "<br>";
}
console.log(output);

//Descending points
var points = [5.0, 3.7, 1.0, 2.9, 3.4, 4.5];
var output = [];
var i;
for (i = 0; i < points.length; i++) {
	points.sort(function (a, b) {
		return b - a
	});
	output += points[i] + "<br>";
}
console.log(output);