snippetjavaMinor
Can this insertion sort be optimized?
Viewed 0 times
thisinsertioncanoptimizedsort
Problem
Could you provide feedback for this code? For arrays of length 2, is it more efficient not to use a sorting algorithm?
By the way, I've noticed "quicksort" is spelt all as one word, but "insertion sort" is spelt as two. Is that right? Would anyone ever say "quicksort sort"?
package insertion.sort;
import java.util.Arrays;
public class InsertionSort {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int[] testArr = {-10, -5, 100, 51, 6, 50};
insertionSort(testArr);
System.out.println(Arrays.toString(testArr));
}
public static void insertionSort(int[] arr) {
for(int i = 1; i 0 && arr[j-1] > temp; j--)
arr[j] = arr[j-1];
arr[j] = temp;
}
}
}By the way, I've noticed "quicksort" is spelt all as one word, but "insertion sort" is spelt as two. Is that right? Would anyone ever say "quicksort sort"?
Solution
As insertion sort is an O(n2) algorithm, there's not much point to optimizing it. For any input that is large enough for you to care about the performance, you would want to pick a sorting algorithm with better bounds. Quicksort, for example, is usually closer to O(n log n).
That said, I'll point out some style issues:
That said, I'll point out some style issues:
- You should never omit optional braces, as you've done for the inner for-loop. Think of it this way: anytime you omit braces, you're a contributing factor to a future coding accident. (Apple learned this lesson the hard way; their new swift language requires braces.)
- Variables can usually be named better than "temp". Renaming
temptoelementToInsert, for example, would make your code self-documenting.
Context
StackExchange Code Review Q#56776, answer score: 6
Revisions (0)
No revisions yet.