First, bubble sort
Algorithm idea: Iterate over the array to be sorted, each time traversing the two elements adjacent to each other, if they are wrong in order to exchange their position, after a trip to sort, the largest element will float the end of the array. Repeat until the sort completes.
Sample Demo:
Algorithm implementation:
for (int i=0;i<array.length-1;i++) {///MAX sort n-1
for (int j=0;j<array.length-i-1;j++) {//number of times required to exchange
if ( Array[j]>array[j+1]) {
int temp=array[j];
ARRAY[J]=ARRAY[J+1];
Array[j+1]=temp
}}
}
Algorithm time complexity: O (N2) Outer loop need to compare n-1 times, inner loop need to compare n times.
Second, select the sort
Algorithm idea: Select a smallest element in the reorder array and swap it with the element in the first position of the array. Then select the smallest element from the remaining elements, swap it with the element in the second position, and if the smallest element is the element of that position, swap it with itself, and so on, until the sort completes.
Sample Demo:
Algorithm implementation:
for (int i=0;i<array.length;i++) {
int min=i;
for (int j=i+1;j<array.length;j++) {
if (Array[j]<array[min]) {
min=j
}
} int temp=array[min];
Array[min]=array[i];
array[i]=temp;
}
Time complexity: O (n2) requires N2/2 comparison and N-time exchange
Third, insert sort
Algorithm idea: Start by traversing the second element of an array, comparing the element to the preceding element, saving the element to a temporary variable if it is smaller than the preceding element, then moving the preceding element back, and then inserting the element into the appropriate location. After each sort completes, the element on the left side of the index must be ordered, but it can also be moved. The lower the inverted array, the higher the sorting efficiency of the algorithm.
Note: Inverted: 5 3 6 2 The inverted entry is 5-3 5-2 3-2 6-2
Sample Demo:
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: O (n2) worst case N2 /2 times comparison, n2 /2 Exchange best case N-1, 0 times Exchange
The above three kinds of simple sorting algorithm (using Java implementation) is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.