Sort an array containing numbers using For loop

我只是一个虾纸丫 提交于 2021-02-18 19:50:43

问题


I am new to Javascript, I have an array which contains numbers.

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

How can i sort it using native For Loop in javascript. I know sort function is available but i want it through for loop.

output should be-

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

回答1:


I would do something like that...

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);

Maybe there are more efficient ways but if you want to use the for loop it's my first idea... Hope it helps




回答2:


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);



回答3:


Under the JavaScript array sort section of W3schools.com it talks about how to compare a value in an array with the others and then order them based on the values being returned. I updated the code to use a for loop to sort values.

//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);


来源:https://stackoverflow.com/questions/38331143/sort-an-array-containing-numbers-using-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!