Home Backend Development PHP Tutorial Some commonly used sorting methods for js arrays

Some commonly used sorting methods for js arrays

Mar 15, 2018 pm 03:41 PM
javascript sort

This article mainly shares with you some commonly used sorting methods for js arrays, including bubble sort, quick sort, insertion sort, etc. I hope it can help you.

1. Bubble sorting (from back to front)

var array = [1,4,-8,-3,6,12,9,8];function sort(arr){    for(var j=0;j<arr.length-1;j++){    //两两比较,如果前一个比后一个大,则交换位置。
       for(var i=0;i<arr.length-1-j;i++){            if(arr[i]>arr[i+1]){                var temp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = temp;
            }
        } 
    }
}
sort(array);
document.write(array);
Copy after login

(1) Compare adjacent elements. If the first one is larger than the second one, swap their positions.

(2) Do the same work for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number.

(3) Repeat the above steps for all elements except the last one.

(4) Continue to repeat the above steps for fewer and fewer elements each time until there is no pair of numbers to compare.

2. Quick sorting: recursive thinking, fast sorting on both sides, improvement of bubble sorting

var array = [1,4,-8,-3,6,12,9,8];
function quickSort(arr){//如果数组长度小于等于1,则返回数组本身
   if(arr.length<=1){        return arr;
   }    //定义中间值的索引
   var index = Math.floor(arr.length/2);    //取到中间值
   var temp = arr.splice(index,1);    //定义左右部分数组
   var left = [];    var right = [];    for(var i=0;i<arr.length;i++){    //如果元素比中间值小,那么放在左边,否则放右边
       if(arr[i]<temp){            left.push(arr[i]);
       }else{            right.push(arr[i]);
       }
   }    return quickSort(left).concat(temp,quickSort(right));
}
document.write(quickSort(array));
Copy after login

Math.floor(x) method is rounded down to return the nearest integer less than or equal to x.

The splice(index,num,item) method adds items to the array or deletes items from the array and returns the deleted item.

index is an integer, the location of the operated item (required)

num is an integer, the number of items to be deleted, if 0, means not to delete (required)

item is a new item added to the array, it can be multiple (optional)

The push() method adds one or more new items to the end of the array and returns the length of the new array

The concat() method connects two or more arrays without changing the original Array, return a new array

3. Insertion sort

var array = [1,4,-8,-3,6,12,9,8];function insertSort(arr){
//假设第0元素是有序序列,第1元素之后是无序的序列。从第1元素开始依次将无序序列的元素插入到有序序列中
   for(var i=1; i<arr.length;i++){        if(arr[i]<arr[i-1]){            //取出无序序列中需要插入的第i个元素
           var temp = arr[i];            //定义有序中的最后一个位置
           var j = i-1;
           arr[i] = arr[j];            //比较大小,找到插入的位置
           while(j>=0&&temp<arr[j]){
               arr[j+1] = arr[j];
               j--;
           };            //插入
           arr[j+1] = temp;
       }
   }
 }
insertSort(array)
document.write(array);
Copy after login

(1) Starting from the first element, the element can be considered to have Sorted

(2) Take out the next element and scan

in the sorted element sequence (3) If the element (already Sorting) is greater than the new element, move the element to the next position

(4) Repeat step 3 until you find the position where the sorted element is less than or equal to the new element

(5) Insert the new element into the next position

(6) Repeat step 2

4. Select sorting

var array = [1,4,-8,-3,6,12,9,8];function selectSort(arr){    for(var i=0;i<arr.length;i++){        //设置当前范围最小值和索引
       var min = arr[i];        var minIndex = i;        //在该范围选出最小值
       for(var j=i+1;j<arr.length;j++){            if(min>arr[j]){
               min = arr[j];
               minIndex = j;
           }
       }        //将最小值插入,并将原来位置的最小值删除
       arr.splice(i,0,min);
       arr.splice(minIndex+1,1);
   }
}
selectSort(array);
document.write(array);
Copy after login

(1) Find the smallest (large) element

in the unsorted sequence (2) and store it in sorting The starting position of the sequence

(3) Then, continue to find the smallest (large) element from the remaining unsorted elements

(4 ) and placed at the end of the sorted sequence.

(5) and so on

The above is the detailed content of Some commonly used sorting methods for js arrays. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to sort photos by date taken in Windows 11/10 How to sort photos by date taken in Windows 11/10 Feb 19, 2024 pm 08:45 PM

This article will introduce how to sort pictures according to shooting date in Windows 11/10, and also discuss what to do if Windows does not sort pictures by date. In Windows systems, organizing photos properly is crucial to making it easy to find image files. Users can manage folders containing photos based on different sorting methods such as date, size, and name. In addition, you can set ascending or descending order as needed to organize files more flexibly. How to Sort Photos by Date Taken in Windows 11/10 To sort photos by date taken in Windows, follow these steps: Open Pictures, Desktop, or any folder where you place photos In the Ribbon menu, click

How to sort emails by sender, subject, date, category, size in Outlook How to sort emails by sender, subject, date, category, size in Outlook Feb 19, 2024 am 10:48 AM

Outlook offers many settings and features to help you manage your work more efficiently. One of them is the sorting option that allows you to categorize your emails according to your needs. In this tutorial, we will learn how to use Outlook's sorting feature to organize emails based on criteria such as sender, subject, date, category, or size. This will make it easier for you to process and find important information, making you more productive. Microsoft Outlook is a powerful application that makes it easy to centrally manage your email and calendar schedules. You can easily send, receive, and organize email, while built-in calendar functionality makes it easy to keep track of your upcoming events and appointments. How to be in Outloo

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to sort WPS scores How to sort WPS scores Mar 20, 2024 am 11:28 AM

In our work, we often use wps software. There are many ways to process data in wps software, and the functions are also very powerful. We often use functions to find averages, summaries, etc. It can be said that as long as The methods that can be used for statistical data have been prepared for everyone in the WPS software library. Below we will introduce the steps of how to sort the scores in WPS. After reading this, you can learn from the experience. 1. First open the table that needs to be ranked. As shown below. 2. Then enter the formula =rank(B2, B2: B5, 0), and be sure to enter 0. As shown below. 3. After entering the formula, press the F4 key on the computer keyboard. This step is to change the relative reference into an absolute reference.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

See all articles