Array sorting, js array sorting
I. Overview 1. Double-Layer Circulation
Sorting is usually implemented by a double loop. The outer loop controls the number of cycles, and the inner loop achieves a single sorting. The index of the outer loop ranges from 1 to arr. length-1. The number of inner loop cycles decreases with the increase of the number of outer loop cycles.
Binary Bubble Method 1. Basic Ideas
Compare two adjacent elements. If the conditions are met, the positions are switched. In this way, the larger elements are moved to the backend.
2. Algorithm Implementation
public static int[] bubbleSort(int[] arr) { for (int i = 1; i < arr.length; i++) { for (int j = 0; j < arr.length - i; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; }Iii. Direct sorting 1. Basic Ideas
The maximum value is filtered out from the unsorted sequence and placed at the end of the unsorted sequence. The outer layer loops once, exchanging the maximum value of the unordered sequence and the position of the last element of the unordered sequence. Other elements remain unchanged. The key is to obtain the index of the maximum value. Direct sorting is faster than Bubble sorting.
Inner Loop entry point: assume that the first element in the unordered sequence, that is, the index 0, is the maximum value, and then compare it with the remaining elements to obtain the index of the maximum value.
2. Algorithm Implementation
public static int[] directSort(int[] arr) { int len = arr.length; int index; for (int i = 1; i < len; i++) { index = 0; for (int j = 1; j <= len - i; j++) { if (arr[index] < arr[j]) { index = j; } int temp = arr[len - i]; arr[len - i] = arr[index]; arr[index] = temp; } } return arr; }Iv. Reverse sorting 1. Basic Ideas
The position of the exchanged index and the two elements of arr. length-1 requires only one loop, and the number of loops is arr. length/2-1.
2. Algorithm Implementation
public static int[] reverseSort(int[] arr) { for (int i = 0; i < arr.length / 2; i++) { int temp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; } return arr; }