Sorting Algorithms
Bubble sort - O(n^2)
- Bubble up the minimum values during each pass
- Repeat below steps n times
- Compare each element with its next item till end (inner loop)
- Swap, if X th element is greater than X+1 th element
Selection sort - O(n^2)
- Divide array into 2 parts = Sorted and Unsorted
- Select the minimum from unsorted for swap
- Repeat below steps n-1 times
- Select the minimum element from unsorted part with element (inner loop)
- Swap it with element at (last index - 1) of sorted array
Insertion sort - O(n^2)
- Insert the element at right place in the left part (for one index per pass)
- Repeat from index 1 to n-1
- Compare element with all its previous items until we receive a lesser value
- Swap if current element is less than previous one
Merge sort - O(n log n)
- Divide and Conquer
- Divide into 2 subarrays
- Sort each one
- Merge them into one
- Example
- Divide array of 8 numbers to 2 sub arrays
- Divide each subarray again into 2 (4 sub arrays)
- Divide each subarray again into 2 (8 sub arrays)
- Merge into 4 subarrays
- Merge into 2 subarrays
- Merge into 1 array
No comments:
Post a Comment
Note: only a member of this blog may post a comment.