The syntax bubble sort function package (ascending descending order)

First, to achieve the basic syntax of this function js

升序
for (var i = 0; i < arr.length; i++) {
            for (var j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    var temp = arr[j + 1];
                    arr [j + 1 ] = arr [j];
                    arr[j] = temp;
                }
            }
        }

Then the function package, since learning is now js basic level, it is not used arr. sort. But with the named function sort, mainly of small white finishing a thought

  function sort(arrIn, fn) {
            for (var i = 0; i < arrIn.length; i++) {
                for (var j = 0; j < arrIn.length - 1 - i; j++) {

                    //   ARR [J]> ARR [J +. 1] This is the time when switching variable ascending, arr [j + 1]> arr [j] is descending at this time performs variable 
                    var Result = Fn (ARR [J], ARR [+ J . 1 ]);
                     IF (Result> 0 ) {
                         var TEMP = arrIn [J + . 1 ];
                        reaches [j + 1 ] = reaches [j];
                        reaches [j] = temp;
                    };
                }

            }
        }
sort(arr, function (a, b) {
            return a - b;
        })

        console.log(arr);

 

 

======================================================

Package forEach () method     

 

Guess you like

Origin www.cnblogs.com/qdxbls/p/11139382.html