The speed is based on the conditions of time complexity, space complexity, etc. You cannot just write a program to see who is faster. There will be accidents. Please consider the performance factors of the algorithm
The if statement of insertion sort should be written in the inner loop condition. The time complexity of your insertion sort is the same as the time complexity of selection sort, so it is slow
Java
/**
* Insertion sort based on exchange
* @param array, Array of Comparable to be Sorted */
public static void sort( Comparable[] array ){
for (int i = 1; i < array.length; i++) {
for(int j=i;j>0&&less(array[j],array[j-1]);j--){
exch(array, j, j-1);
}
}
}
The speed is based on the conditions of time complexity, space complexity, etc. You cannot just write a program to see who is faster. There will be accidents. Please consider the performance factors of the algorithm
Theoretically speaking, selection sort <insertion sort <Hill sort, but the actual time-consuming depends on the sample and specific implementation.
Create 10,000 use cases to test
The if statement of insertion sort should be written in the inner loop condition. The time complexity of your insertion sort is the same as the time complexity of selection sort, so it is slow
Java
/**
* Insertion sort based on exchange
* @param array, Array of Comparable to be Sorted
*/
public static void sort( Comparable[] array ){
for (int i = 1; i < array.length; i++) {
for(int j=i;j>0&&less(array[j],array[j-1]);j--){
exch(array, j, j-1);
}
}
}