B2B - Sorting Algorithms
K3K, 28 September 2020
Table of Contents
- Definition
- Comparision Sorts 1. Core Idea 1. Sample Implementation 1. Extras & Gotchas
- Non-Comparision Sorts
- References
Because every interview got a question or two about them.
Hewwo, this is captain K speaking.
This is the start of the B2B[Back 2 Basics] series where I brush up on programming concepts I learnt from school.
The sample code will be written in Java and/or Python.
Definition
Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements.
Comparision Sorts
- Insertion Sort
-
Core Idea
Assuming we're looping from the array's start:
For each element, move it towards the start of the array until [current >= previous].
This ensures that the traversed portion of the array is sorted.
Example:
Array: [1,5,6,3]
Iteration 1: (1) => got nothing previous to compare to => not moved.
Iteration 2: (5) => (5) >= (1) => not moved.
Iteration 3: (6) => (6) >= (5) => not moved.
Iteration 4: (3)
=> (3) >= (6) && (3) >= (5)
=> move (3) up 2 positions
=> Sorted Array: [1,3,5,6].Sample Implementation
int* a = [3,6,2]; int tempNum; int curPos = 0; for(int i = 0; i < a.length;i++){ curPos = i; while(curPos > 0 || a[i] < a[curPos - 1]){ curPos--; } if(curPos != i){ //swaps a[i] and a[curPos] } }
Extras & Gotchas
- Costly if the element sits too far from its sorted position.
- Bubble Sort
-
Lorem ipsum dolor vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing accumsan eu faucibus. Integer ac pellentesque praesent.
- Quicksort
-
Lorem ipsum dolor vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing accumsan eu faucibus. Integer ac pellentesque praesent.
- Merge Sort
-
Lorem ipsum dolor vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing accumsan eu faucibus. Integer ac pellentesque praesent.
- Heapsort
-
Lorem ipsum dolor vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing accumsan eu faucibus. Integer ac pellentesque praesent.
Non-Comparision Sorts
- Bucket Sort
-
Lorem ipsum dolor vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing accumsan eu faucibus. Integer ac pellentesque praesent.
- Counting Not
-
Lorem ipsum dolor vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing accumsan eu faucibus. Integer ac pellentesque praesent.
- Radix 3
-
Lorem ipsum dolor vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing accumsan eu faucibus. Integer ac pellentesque praesent.
References
- For list of sorting algs: Wikipedia
- For in-depth info on a specific alg: GeeksforGeeks