Simple Sorting: Selection Sort
The selection sort is a little bit more involved than the bubble sort. This algorithm basically makes a pass through all the values for picking the shortest one. This shortest value is swapped with the leftmost value on each pass. The sorted values accumulate on the left (in the bubble sort they accumulated on the right).
Process
- Start on the left (outer loop)
- Record first index as minimum value by default
- Compare each value on the right (inner loop)
- If a shortest value exists, replace the minimum index with the current one.
- Swap outer value with the minimum
- Repeat above steps until end of outer loop
Java:
Python
The selection sort and bubble sort have the same number of comparisons [N*(N-1)/2]. However, the selection sort is faster because there are fewer swaps. The selection sort runs in O(N2) time.
Comments
Post a Comment