1. The JavaScript sort() method is the most commonly used and fastest method!

  • Definition: Sorts arrays in order of size
  • @params: It can be nothing, or it can be a function
  • @return: The sorted array
  • Whether to change the original array: Change
Method: arr.sort() : sort method cannot handle sorting of numbers above 10 without passing an argument (it defaults to sorting by the first character of each item, which is not what we want)
  • To do a normal multi-digit SORT, pass a function to SORT that returns A-B in ascending order and B-A in descending order:
  • arr.sort(function(a,b){return a-b; });
  • Arr. Sort ((a,b) => a-b);
“Ascending”

“Descending”

2. Bubble Sort (back-to-front)

Click the link to copy the code console above to view the output

Copy the code

  1. Compare adjacent elements. If the first one is bigger than the second, switch them.
  2. Do the same for each pair of adjacent elements, starting with the first pair and ending with the last pair. 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 repeating the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.

3. Quick sort: recursive thought, quick sort on both sides, improvement of bubble sort

Click the link to copy the code console above to view the output

Copy the code

The Math.Floor (x) method is rounded down and returns the nearest integer less than or equal to x. The splice(index,num,item) method adds or removes items from an array and returns the deleted items.

  1. Index is an integer, the position of the item being operated on (required)
  2. Num is an integer, the number of items to delete, if 0, not to delete (must)
  3. Item is a new item added to the array, and can be multiple (optionally)

    The concat() method concatenates two or more arrays without changing the original array and returns a new array

4. Insert sort

Click the link to copy the code console above to view the output

Copy the code

  1. Find the smallest (largest) element in an unsorted sequence
  2. And put them at the beginning of the sort sequence
  3. Then, we continue to look for the smallest (largest) element from the remaining unsorted elements
  4. Then put it at the end of the sorted sequence.
  5. And so on

6. Native JavaScript array sorting

Methods/Procedures

1. Get the largest element in the array

2. Put the maximum value at the end of the array
  • Define an intermediate variable to exchange the maximum value with the value of the last element.
  • Define a variable to hold the position of the maximum value;

3. Use a second loop to perform step 2:

4. Encapsulate step 3 in a function:

Note:

1. Numbers are sorted in ascending order! 2. This method changes the original array!