使用JavaScript對數字數組進行排序


所述的JavaScript的Array.sort()方法被用來就地數組元素進行排序,並返回排序后的數組。此函數以字符串格式對元素進行排序。它對字符串數組有效,但對數字無效。例如:如果數字按字符串排序。例:

輸入:[12,25,31,23,75,81,100]錯誤的輸出:[100、12、23、25、31、75、81]正確的輸出:[12、23、25、31、75、81、100]

示例:本示例以字符串格式對數組元素進行排序。

<script>
// Declare and initialize original array var marks = [12, 25, 31, 23, 75, 81, 100];
// Print Before Sortring Array  document.write("Original Array</br>");  document.write(marks);
document.write("</br>");
// Call sort fucntion marks.sort();
document.write("</br>After Sorting in Ascending Order</br>");
// Print Srted Numeric Array  document.write(marks);  </script>

 

輸出:

原始陣列12,25,31,23,75,81,100
升序排序后100,12,23,25,31,75,81

那么,如何對數字數組元素進行排序?
有兩種方法可以對數字數組進行升序排序。

  • 使用比較功能

  • 通過創建循環

使用比較功能:我們可以創建一個比較功能,該功能返回負值,零值或正值。
句法:

函數(a,b){返回a-b}
  • 負值(a> b)=> a將放置在b之前

  • 零值(a == b)=>不變

  • 正值(a <b)=> a將位於b之后

示例:本示例使用compare函數對數組元素進行升序排序。

<script>
// Declare and initialize an Array var marks = [12, 25, 31, 23, 75, 81, 100];
// Print Before sortring array  document.write("Original Array</br>");  document.write(marks);
document.write("</br>");
// Sort elements using compare method  marks.sort(function(a, b){return a - b});
document.write("</br>After sorting in Ascending order</br>");
// Print sorted Numeric array  document.write(marks);  </script>

 

輸出:

原始陣列12,25,31,23,75,81,100
升序排序后12,23,25,31,75,81,100

現在,我們要以降序對數組進行排序,而不需要更改比較函數。句法:

函數(a,b){返回b-a}
  • 負值(b <a)=> a將位於b之后

  • 零值(a == b)=>不變

  • 正值(b> a)=> a將位於b之前

示例:本示例使用compare函數對數組元素進行降序排序。

<script>
// Declare and initialize an Array var marks = [12, 25, 31, 23, 75, 81, 100];
// Print Before sortring array  document.write("Original Array</br>");  document.write(marks);
document.write("</br>");
// Sort elements using compare method  marks.sort(function(a, b){return b - a});
document.write("</br>After sorting in Ascending order</br>");
// Print sorted Numeric array  document.write(marks);  </script>

 

輸出:

原始陣列12,25,31,23,75,81,100
升序排序后100,81,75,31,25,23,12

創建循環:我們還可以使用循環對數組元素進行排序。在這里,我們將使用冒泡排序(簡單排序技術)對數組元素進行升序排序。例:

<script>
// Sorting function function Numeric_sort(ar) {
    var i = 0, j;
    while (i < ar.length) {          j = i + 1;          while (j < ar.length) {
            if (ar[j] < ar[i]) {                 var temp = ar[i];                  ar[i] = ar[j];                  ar[j] = temp;              }              j++;          }          i++;      }  }
// Original Array var arr = [1, 15, 10, 45, 27, 100];
// Print Before sortring array  document.write("Original Array</br>");  document.write(arr);
document.write("</br>");
// Function call  Numeric_sort(arr);
document.write("</br>Sorted Array</br>");
// Print sorted Numeric array  document.write(arr);  </script>

 

輸出:

原始陣列1,15,10,45,27,100
排序數組1,10,15,27,45,100


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM