Sort Usually implemented by a double-layer loop, the outer loop controls the number of loop rounds, and the inner loop implements single sorting. The index of the outer loop is from 1 to arr.length-1, and the number of iterations of the inner loop decreases as the number of iterations of the outer loop increases.
Compare adjacent If the two elements meet the conditions, they will swap positions, so that the larger element will be moved to the back.
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; }
Filter out the maximum value from the unsorted sequence and place it at the end of the unsorted sequence. The outer loop loops once, exchanging the maximum value of the unsorted sequence with the position of the last element of the unsorted sequence. The positions of other elements remain unchanged. The key is to obtain the index of the maximum value. Direct sort is faster than bubble sort.
Inner loop entry point: Assume that the first element in the unsorted sequence, that is, the element with index 0, is the maximum value, and then compare it with the remaining elements to obtain the index of the maximum value.
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; }
To exchange the positions of two elements whose index sum is arr.length-1, only one loop is needed, and the number of loops is arr.length/2-1.
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; }
The above is the detailed content of Detailed introduction to array sorting. For more information, please follow other related articles on the PHP Chinese website!