让一个数字和后面的数字进行依次的比较
如果发现前面的大于后面的
就把前面的和后面的进行位置互换
外层从0开始,内层从0+1开始
代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> </html> <script> var arr = [7,8,1,4,5,6,2,3,5,9,7]; for (var i=0 ;i<arr.length;i++){ //8 //1 for (var j =i+1;j<=arr.length;j++){ if (arr[i]>arr[j]){ var c = arr[i]; arr[i] = arr[j]; arr[j] = c; // document.write(arr+'<br>');//可以看到每次的变化 } } } document.write(arr); </script>
显示效果:
升序:
var arr = [7,8,1,4,5,6,2,3,5];
arr.sort();
document.write(arr);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> </html> <script> var arr = [7,8,1,4,5,6,2,3,5]; arr.sort(function (a, b) { return a-b; }) document.write(arr); </script>
显示效果:
调用封装好的方法 降序:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> </html> <script> var arr = [7,8,1,4,5,6,2,3,5]; arr.sort(function (a, b) { return b-a; }) document.write(arr); </script>
显示效果: