使用For循环对包含数字的数组进行排序 [英] Sort an array containing numbers using For loop

查看:46
本文介绍了使用For循环对包含数字的数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java语言的新手,我有一个包含数字的数组.

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

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

如何使用javascript中的本机For Loop对其进行排序.我知道排序功能是可用的,但我希望它通过for循环.

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

输出应为-

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

推荐答案

我会做类似的事情...

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

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

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

这篇关于使用For循环对包含数字的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆