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

JS implements simple sorting

小云云
Release: 2018-03-19 16:15:19
Original
1393 people have browsed it

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]);
     }
Copy after login

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]);
     }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template