在 Javascript 中使用 for 循环对数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7870961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:35:41  来源:igfitidea点击:

Sorting arrays using for loop in Javascript

javascript

提问by methuselah

Is it possible to sort arrays in ascending/descending order using the for loopJavaScript?

是否可以使用for 循环JavaScript按升序/降序对数组进行排序?

I've been learning JS going through a few practice questions in a textbook before a class test.

在课堂测试之前,我一直在通过教科书中的一些练习题来学习 JS。

Any pointers would be appreciated!

任何指针将不胜感激!

a = Number(prompt("a:"));
b = Number(prompt("b:"));
c = Number(prompt("c:"));
d = Number(prompt("d:"));
e = Number(prompt("e:"));

// find largest element
var test = [a, b, c, d, e];
var biggest = -Infinity;
var biggest_index = -1; {
    for (i = 0; i < test.length; i++) {
        if (test[i] > biggest) {
            biggest = test[i];
            biggest_index = i;
        }
        else;
    }
    alert("The biggest element is " + biggest + " at index " + biggest_index);
}

// move largest element of array to the last index
test[test.length] = biggest;

// get rid of copy
test[biggest_index] = 0;
alert("Unsorted: " + test);

// shuffle ??

采纳答案by wong2

If you want to get the max/min number in an array, why not use Math.max/Math.min?

如果您想获取数组中的最大/最小数,为什么不使用Math.max/Math.min

If you want to sort the array, you can use sortmethod:

如果要对数组进行排序,可以使用sort方法:

var sorted = [3, 1, 6, 2].sort(); // sort ascending  
var sorted = [3, 1, 6, 2].sort(function(a, b){
    return b - a;
}); // sort descending 

回答by Daryl

Sure it's possible. First you should decide which algorithm you want to sort with. See here for some great visual examples http://www.sorting-algorithms.com/

当然有可能。首先,您应该决定要使用哪种算法进行排序。在这里查看一些很棒的视觉示例http://www.sorting-algorithms.com/

From your example though, you'll need another for loop. So far you're finding the biggest, you'll need another loop to repeat your logic, but find the second biggest, than third, than 4th. etc.

但是,从您的示例中,您将需要另一个 for 循环。到目前为止,你找到了最大的,你需要另一个循环来重复你的逻辑,但找到第二大,比第三大,比第四大。等等。

回答by Icarus

javascript has a sort function for arrays.

javascript 有一个数组排序功能。

You can do

你可以做

alert("Sorted: "+ test.sort());

回答by John Slegers

If you're just looking for an efficient way to sort an array, it's best to just use the built-in sort()method.

如果您只是在寻找一种对数组进行排序的有效方法,最好只使用内置sort()方法

Using it can be as simple as this :

使用它可以像这样简单:

var unsortedArray = [12, 55, 35, 11, 88, 13, 6];
var sortedArray = unsortedArray.sort();


If you don't want to use the built-in sort()method for some reason (eg. educational purposes), you should do some research on sorting algorithms.

如果sort()出于某种原因(例如教育目的)不想使用内置方法,则应该对排序算法进行一些研究。

These are some of the most popular sorting algorithms out there :

这些是一些最流行的排序算法:

回答by twknab

I was actually working on manually sorting javascript arrays with for loops today. While the code below does assume you're feeding it arrays (e.g, does not check for types), here was a solution I was able to get using forloops only, no built-in sorting methods and no new array creation:

我今天实际上正在使用 for 循环手动对 javascript 数组进行排序。虽然下面的代码确实假设您正在为它提供数组(例如,不检查类型),但这里有一个解决方案,我for只能使用循环,没有内置的排序方法,也没有创建新的数组:

Sorting Greatest to Least

排序最大到最小

function sortGreatest(arr) {
  // manually sort array from largest to smallest:
  // loop forwards through array:
  for (let i = 0; i < arr.length; i++) {
    // loop through the array, moving forwards:
    // note in loop below we set `j = i` so we move on after finding greatest value:
    for (let j = i; j < arr.length; j++) {
      if (arr[i] < arr[j]) {
        let temp = arr[i]; // store original value for swapping
        arr[i] = arr[j]; // set original value position to greater value
        arr[j] = temp; // set greater value position to original value
      };
    };
  };
  return arr;
};

console.log(sortGreatest([10,9,1000,12,-11,3]));
// => [ 1000, 12, 10, 9, 3, -11 ]

Sorting Least to Greatest

从小到大排序

function sortLeast(arr) {
  // manually sort array from smallest to largest:
  // loop through array backwards:
  for (let i = arr.length-1; i >= 0; i--) {
    // loop again through the array, moving backwards:
    for (let j = i; j >= 0; j--) {
      if (arr[i] < arr[j]) {
        let temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
      };
    };
  };
  return arr;
};
console.log(sortLeast([10,9,1000,12,-11,3]));
// => [ -11, 3, 9, 10, 12, 1000 ]

回答by Fatah Banan Wijaya

this for A to B

这对于 A 到 B

function smallTobig(numbers) {

let A_B = []
    for(let i = 0; i < numbers.length; i++) {
     for(let j = i; j < numbers.length; j++) {
        if (numbers[i] > numbers[j]) {
            let temp = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = temp;
        }
    }
    A_B.push(numbers[i])
}
return A_B
}
console.log(smallTobig([5, 2, 1, 4])); 
console.log(smallTobig([999, 5, 0, 1, 4, 998])); 
console.log(smallTobig([15, 32, 11, 14]));
console.log(smallTobig([5, 4, 3, 2, 1, 0]));
console.log(smallTobig([123, 321, 143, 313]));

this for B to A

这对于 B 到 A

function bigTosmall(numbers) {

let B_A = []
    for(let i = 0; i < numbers.length; i++) {
     for(let j = i; j < numbers.length; j++) {
        if (numbers[i] < numbers[j]) {
            let temp = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = temp;
        }
    }
    B_A.push(numbers[i])
}
return B_A
}
console.log(bigTosmall([5, 2, 1, 4])); 
console.log(bigTosmall([999, 5, 0, 1, 4, 998])); 
console.log(bigTosmall([15, 32, 11, 14]));
console.log(bigTosmall([5, 4, 3, 2, 1, 0]));
console.log(bigTosmall([123, 321, 143, 313]));