Array Sorting Algorithm and Sorting Algorithm
Array Sorting Algorithm (I) Bubble Sorting
Basic Idea: Compare adjacent element values. If conditions are met, swap element values, move smaller elements to the front of the array, and move larger elements to the back of the array.
Algorithm:
The bubble algorithm is implemented by a double-layer loop. The outer loop controls the sorting round, which is generally reduced by one by the length of the sorted array. The inner loop is mainly used to compare the size of each adjacent element in the array to determine whether to swap the position. The number of comparisons and exchanges decreases with the number of sorting turns.
Algorithm Implementation:
1 public class Bubble {2 public static void main (String [] args) {3 int [] array = {63,4, 24,1, 3,15}; 4 Bubble sorter = new Bubble (); 5 sorter. sort (array); 6} 7 // bubble sort 8 public void sort (int [] array) {9 for (int I = 1; I <array. length; I ++) {// sorting round, array length-110 for (int j = 0; j <array. length-I; j ++) {// comparison of the inner layer. At the end of each round, an 11 if (array [j]> array [j + 1]) is compared. {12 int temp = array [j]; 13 array [j] = array [j + 1]; 14 array [j + 1] = temp; 15} 16} 17} 18 showArray (array); 19} 20 // display array element 21 public void showArray (int [] array) {22 for (int I: array) {23 System. out. print (I + ""); 24} 25} 26}
(2) directly select sorting
Faster than Bubble Sorting
Basic Idea: Compare the specified sorting position with other array elements. If the conditions are met, the element values are exchanged.
Example:
Initial Value: 63 4 24 1 3 15
First round: 15 4 24 1 3 63
Round 2: 15 4 3 1 24 63
Round 3: 1 4 3 15 24 63
Round 4: 1 3 4 15 24 63
Round 5: 1 3 4 15 24 63
Explanation: First, find the largest position in the six numbers to exchange with the last number, and then find the largest number in the first five numbers and the last second switching position, so that length-1
Algorithm Implementation:
1 public class Select {2 public static void main (String [] args) {3 int array [] = {63,4, 24,1, 3,15}; 4 Select sorter = new Select (); 5 sorter. sort (array); 6} 7 // directly select sort 8 public void sort (int [] array) {9 int index; 10 for (int I = 1; I <array. length; I ++) {// The sorting round is still the array length-111 index = 0; 12 for (int j = 1; j <= array. length-I; j ++) {// compare the inner layer, find the maximum number of positions 13 if (array [j]> array [index]) {14 index = j; 15} 16} 17 int temp = array [array. length-I]; 18 array [array. length-I] = array [index]; 19 array [index] = temp; 20} 21 showArray (array ); 22} 23 // display array 24 private void showArray (int [] array) {25 for (int I: array) {26 System. out. print (I + ""); 27} 28} 29}