插入排序算法的以下
Java实现出现在Noel Markham公开的Java编程访谈的第28页上:
public static List<Integer> insertSort(final List<Integer> numbers) {
final List<Integer> sortedList = new LinkedList<>();
originalList: for (Integer number : numbers) {
for (int i = 0; i < sortedList.size(); i++) {
if (number < sortedList.get(i)) {
sortedList.add(i, number);
continue originalList;
}
}
sortedList.add(sortedList.size(), number);
}
return sortedList;
}
我的一位同事回顾了这段代码后发现,作为对“请实施插入排序算法”的面试问题的回答,这是不可接受的.他认为数组对于排序列表来说是更合适的数据结构.但是,正如马克姆在同一页上解释的那样:
A linked list is very efficient in adding elements in the middle of
the list, simply by rearranging the pointers of the nodes in the list.
If an ArrayList had been used, adding elements to the middle would be
expensive. An ArrayList is backed by an array, so inserting at the
front or middle of the list means that all subsequent elements must be
shifted along by one to a new slot in the array. This can be very
expensive if you have a list with several million rows, especially if
you are inserting early in the list.
这是可接受的实施吗?
最佳答案 考虑以下用于插入排序的伪代码:
for i ← 1 to length(A) - 1
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1
end while
end for
来源:http://en.wikipedia.org/wiki/Insertion_sort
1)所以,在这个过程中,你持有每个元素并将它与前一个元素进行比较并交换前一个元素是否大于当前元素并且这种情况一直发生直到条件不满足为止.
2)算法通过逐个元素交换而不是通过将元素插入到它应该被放置的位置来工作.注意: – 每个交换是o(1).
3)因此,在这种形式中,如果使用列表,则需要执行2个操作,将前一个和当前元素连接起来,反之亦然.另一方面,排序数组只需要一步.
4)因此,在这种方法中,排序数组比列表更有意义.
Now, if the approach of insertion sort was directly inserting the current element at the place where it is fitting, a linked list would have worked better.
注意: – 排序的数组或排序的链表,整个过程将是相同的,它是中间步骤产生差异而不是排序.