Home  >  Article  >  Web Front-end  >  JS implements simple sorting

JS implements simple sorting

小云云
小云云Original
2018-03-19 16:15:191340browse

This article mainly shares with you JS to implement simple sorting, including bubble sorting and selection sorting. I hope it can help everyone.

1. Bubble sorting: compare two adjacent elements in sequence, exchange sizes

var arr = [3, 5, 15, 36, 36, 27, 2, 38];
    //冒泡排序
    function bubbleSort(arr) {
        var len = arr.length;
        for (var i = 0; i < len - 1; i++) {
            for (var j = 0; j < len - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    var temp = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        //return arr;
    }
    bubbleSort(arr);
     for (var i = 0; i < arr.length; i++) {
            alert(arr[i]);
     }

2. Selection sorting: select the most valuable element, Put it first, and then continue to select the best value among the remaining elements.

//选择排序
  var arr = [3, 5, 15, 36, 36, 27, 2, 38];
    function selectSort(arr) {
        var len = arr.length;
        var minIndex, temp;
        for (var i = 0; i < len - 1; i++) {
            minIndex = i;
            for (var j = i + 1; j < len; j++) {
                //寻找最小的值,保存索引
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }
 selectSort(arr);
  for (var i = 0; i < arr.length; i++) {
            alert(arr[i]);
     }

Related recommendations:

php simple sorting bubble sort and selection sort

The above is the detailed content of JS implements simple sorting. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn