Sorting algorithms/Insertion sort – Rosetta Code

Sorting Algorithm This is a sorting algorithm. It may be applied to a set of data in order to sort it. An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases: (i) small n, (ii) as the final finishing-off algorithm for O(n logn) algorithms such as mergesort and quicksort. Uses binary search via std::upper_bound() to find the insertion position in logarithmic time and then performs the insertion via std::rotate() in linear time. This exerpt contains just enough of the procedure division to show the sort itself. The appropriate data division entries can be inferred. See also the entry for the Bubble sort for a full program. In ISO Fortran 90 and above the intrinsic function CSHIFT can be used to shift the elements in the array but in practice is slower than the above example Note: This example relies on the supporting procedures 'sortop', and 'demosort' in Bubble Sort. The full demosort exercises the named sort of a list with op = 'numeric', 'string', '>,>,' (lexically gt, descending),'>,' (numerically gt, descending), a custom comparator, and also a string. Using some built-in algorithms (warning: not stable, due to the lack of an 'upper bound' binary search function) The following solution uses an 'industrial strength' implementation of bsearch (binary search) that requires the following control structure: bsearch is the only non-trivial part of this solution, and so we include its complete specification: Assuming the input array is sorted, bsearch/1 returns the index of the target if the target is in the input array, and otherwise (-1 - ix), where ix is the insertion point that would leave the array sorted. This is a direct translation of the pseudo-code above, except that it has been modified to compensate for MATLAB's 1 based arrays. Works with SWI-Prolog. Insertion sort inserts elements of a list in a sorted list. So we can use foldl to sort a list. Alternative version which doesn't swap elements but rather removes and inserts the value at the correct place: Source.


Яндекс.Метрика Рейтинг@Mail.ru Free Web Counter
page counter
Last Modified: April 23, 2016 @ 6:05 am