Sorting algorithms •
Insertion sort applied to a list of
n elements, assumed to be all different and initially in random order. On average, half the elements in a list
A1 ...
Aj are less than element
Aj+1, and half are greater. Therefore, the algorithm compares the (
j + 1)th element to be inserted on the average with half the already sorted sub-list, so
tj =
j/2. Working out the resulting average-case running time yields a quadratic function of the input size, just like the worst-case running time. •
Quicksort applied to a list of
n elements, again assumed to be all different and initially in random order. This popular
sorting algorithm has an average-case performance of O(
n log(
n)), which contributes to making it a very fast algorithm in practice. But given a worst-case input, its performance degrades to O(
n2). Also, when implemented with the "shortest first" policy, the worst-case space complexity is instead bounded by O(log(
n)). • Heapsort has O(n) time when all elements are the same. Heapify takes O(n) time and then removing elements from the heap is O(1) time for each of the n elements. The run time grows to O(nlog(n)) if all elements must be distinct. •
Bogosort has O(n) time when the elements are sorted on the first iteration. In each iteration all elements are checked if in order. There are n! possible permutations; with a balanced random number generator, almost each permutation of the array is yielded in n! iterations. Computers have limited memory, so the generated numbers cycle; it might not be possible to reach each permutation. In the worst case this leads to O(∞) time, an infinite loop.
Data structures •
Linear search on a list of
n elements. In the absolute worst case, the search must visit every element once. This happens when the value being searched for is either the last element in the list, or is not in the list. However, on average, assuming the value searched for is in the list and each list element is equally likely to be the value searched for, the search visits only
n/2 elements. == See also ==