Three simple sorting algorithms (implemented in java) and three sort algorithms java
I. Bubble Sorting
Algorithm idea: traverse the array to be sorted, and traverse the adjacent two elements each time. If their order is wrong, they will switch their positions. After sorting, the largest element will float the end of the array. Repeat the operation until the sorting is completed.
Example:
Algorithm Implementation:
1 for (int I = 0; I <array. length-1; I ++) {// a maximum of N-1 orders 2 for (int j = 0; j <array. length-i-1; j ++) {// number of times to be exchanged 3 if (array [j]> array [j + 1]) {4 int temp = array [j]; 5 array [j] = array [j + 1]; 6 array [j + 1] = temp; 7} 8} 9}
Algorithm time complexity: the outer loop of O (n2) needs to be compared n-1 times, and the inner loop needs to be compared n times.
Ii. Select sorting
Algorithm idea: select the smallest element from the array to be sorted and exchange it with the element at the first position of the array. Then select the smallest element from the remaining element and exchange it with the element in the second position. If the smallest element is the element in the second position, it is exchanged with itself, and so on until the sorting is completed.
Example:
Algorithm Implementation:
1 for(int i=0;i<array.length;i++){ 2 int min=i; 3 for(int j=i+1;j<array.length;j++){ 4 if(array[j]<array[min]){ 5 min=j; 6 } 7 } 8 int temp=array[min]; 9 array[min]=array[i];10 array[i]=temp;11 }
Time Complexity: O (n2) requires n2/2 comparisons and n exchanges
Iii. Insert sorting
Algorithm idea: traverse from the second element of the array and compare the element with the previous element. If the element is smaller than the previous one, save the element to the temporary variable, move the preceding element to a proper position. After each sorting, the elements on the left of the index must be ordered but can be moved. For arrays with less inversion, the sorting efficiency of this algorithm is higher.
Note: inverted: 5 3 6 2 inverted items are 5-3 5-2 3-2 6-2
Example:
Algorithm Implementation:
for(int i=1;i<array.length;i++){ for(int j=i;j>0&&array[j]<array[j-1];j--){ int temp=array[j]; array[j]=array[j-1]; array[j-1]=temp; } }
Time Complexity: n2/2 Comparison in the worst case of O (n2), n2/2 exchange, N-1, 0 exchange
Note: If you have any questions about cainiao, please correct them.