Skip to content

Commit

Permalink
Added Insertion Sort & Updated Read Me
Browse files Browse the repository at this point in the history
  • Loading branch information
anugraheeth committed Nov 15, 2024
1 parent 893d215 commit 6d690b2
Show file tree
Hide file tree
Showing 5 changed files with 191 additions and 3 deletions.
107 changes: 107 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,113 @@ These tuples are then used by the visualization component to:
2. Swap the bars' positions (when isSwap is true)
3. Control the timing and sequence of the animations

### Selection Sort Implementation

```javascript
function selectionSort(array) {
const auxiliaryArray = [...array];
const animations = [];
const n = auxiliaryArray.length;

for (let i = 0; i < n - 1; i++) {
let minIndex = i;
for (let j = i + 1; j < n; j++) {
animations.push([j, minIndex, false]); // Comparison
if (auxiliaryArray[j] < auxiliaryArray[minIndex]) {
minIndex = j;
}
}
if (minIndex !== i) {
animations.push([i, minIndex, true]); // Swap
[auxiliaryArray[i], auxiliaryArray[minIndex]] =
[auxiliaryArray[minIndex], auxiliaryArray[i]];
}
}
return animations;
}
```
The Selection Sort algorithm:
- Divides the array into a sorted and an unsorted region.
- Repeatedly selects the smallest element from the unsorted region and moves it to the end of the sorted region.
- Creates an animation array to track all comparisons and swaps, returning an array of animation tuples in the format: [index1, index2, isSwap].
- For comparisons: [3, 4, false] means "compare elements at index 3 and 4".
- For swaps: [3, 4, true] means "swap elements at index 3 and 4".
- Preserves the original array by working on a copy.

### Insertion Sort Implementation

```javascript
function insertionSort(array) {
const auxiliaryArray = [...array];
const animations = [];
const n = auxiliaryArray.length;

for (let i = 1; i < n; i++) {
let key = auxiliaryArray[i];
let j = i - 1;

while (j >= 0 && auxiliaryArray[j] > key) {
animations.push([j, j + 1, false]); // Comparison
animations.push([j, j + 1, true]); // Swap
auxiliaryArray[j + 1] = auxiliaryArray[j];
j--;
}
auxiliaryArray[j + 1] = key;
}
return animations;
}
```
The Insertion Sort algorithm:
- Builds a sorted array one element at a time.
- Compares the current element with the sorted elements and places it in the correct position.
- Creates an animation array to track all comparisons and swaps, returning an array of animation tuples in the format: [index1, index2, isSwap].
- For comparisons: [3, 4, false] means "compare elements at index 3 and 4".
- For swaps: [3, 4, true] means "swap elements at index 3 and 4".
- Preserves the original array by working on a copy.

### Quick Sort Implementation

```javascript
function quickSort(array) {
const animations = [];

const sort = (arr, left, right) => {
if (left < right) {
const pivotIndex = partition(arr, left, right);
sort(arr, left, pivotIndex - 1);
sort(arr, pivotIndex + 1, right);
}
};

const partition = (arr, left, right) => {
const pivot = arr[right];
let i = left - 1;

for (let j = left; j < right; j++) {
animations.push([j, right, false]); // Comparison
if (arr[j] < pivot) {
i++;
animations.push([i, j, true]); // Swap
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
animations.push([i + 1, right, true]); // Swap pivot
[arr[i + 1], arr[right]] = [arr[right], arr[i + 1]];
return i + 1;
};

sort(array, 0, array.length - 1);
return animations;
}
```
The Quick Sort algorithm:
- Uses a divide-and-conquer approach to sort the array.
- Selects a pivot and partitions the array into elements less than and greater than the pivot.
- Creates an animation array to track all comparisons and swaps, returning an array of animation tuples in the format: [index1, index2, isSwap].
- For comparisons: [3, 4, false] means "compare elements at index 3 and 4".
- For swaps: [3, 4, true] means "swap elements at index 3 and 4".
- Preserves the original array by working on a copy.

### Visualization Logic
```javascript
const visualizeSort = (animations) => {
Expand Down
22 changes: 22 additions & 0 deletions src/algorithms/insertionSort.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export default function insertionSort(array) {
const auxiliaryArray = [...array];
const animations = [];
insertionSortHelper(auxiliaryArray, animations);
return animations;
}

function insertionSortHelper(array, animations) {
for (let i = 1; i < array.length; i++) {
let current = array[i];
let j = i - 1;

animations.push([i, j, false]);

while (j >= 0 && array[j] > current) {
animations.push([j + 1, j, true]);
array[j + 1] = array[j];
j--;
}
array[j + 1] = current;
}
}
52 changes: 52 additions & 0 deletions src/algorithms/mergeSort.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
export default function mergeSort(array) {
const auxiliaryArray = [...array];
const animations = [];
mergeSortHelper(array, auxiliaryArray, 0, array.length - 1, animations);
return animations;
}

function mergeSortHelper(mainArray, auxiliaryArray, startIdx, endIdx, animations) {
if (startIdx === endIdx) return;

const middleIdx = Math.floor((startIdx + endIdx) / 2);

// Recursively divide the array into halves
mergeSortHelper(auxiliaryArray, mainArray, startIdx, middleIdx, animations);
mergeSortHelper(auxiliaryArray, mainArray, middleIdx + 1, endIdx, animations);

// Merge the sorted halves
merge(mainArray, auxiliaryArray, startIdx, middleIdx, endIdx, animations);
}

function merge(mainArray, auxiliaryArray, startIdx, middleIdx, endIdx, animations) {
let i = startIdx;
let j = middleIdx + 1;
let k = startIdx;

while (i <= middleIdx && j <= endIdx) {
// Animation to compare elements at indices i and j
animations.push([i, j, false]);

if (auxiliaryArray[i] <= auxiliaryArray[j]) {
// Animation to overwrite element at k with auxiliaryArray[i]
animations.push([k, auxiliaryArray[i], true]);
mainArray[k++] = auxiliaryArray[i++];
} else {
// Animation to overwrite element at k with auxiliaryArray[j]
animations.push([k, auxiliaryArray[j], true]);
mainArray[k++] = auxiliaryArray[j++];
}
}

while (i <= middleIdx) {
// Animation to overwrite element at k with auxiliaryArray[i]
animations.push([k, auxiliaryArray[i], true]);
mainArray[k++] = auxiliaryArray[i++];
}

while (j <= endIdx) {
// Animation to overwrite element at k with auxiliaryArray[j]
animations.push([k, auxiliaryArray[j], true]);
mainArray[k++] = auxiliaryArray[j++];
}
}
1 change: 0 additions & 1 deletion src/algorithms/quickSort.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ export default function quickSort(array) {
const auxiliaryArray = [...array];
const animations = [];
quickSortHelper(auxiliaryArray, 0, auxiliaryArray.length - 1, animations);
console.log("Sorted array:", auxiliaryArray);
return animations;
}

Expand Down
12 changes: 10 additions & 2 deletions src/components/graph.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import "../assets/graph.css";
import bubbleSort from "../algorithms/bubbleSort";
import quickSort from "../algorithms/quickSort";
import selectionSort from "../algorithms/selectionSort";
import insertionSort from "../algorithms/insertionSort";

function Graph() {
const [array, setArray] = useState([]);
Expand Down Expand Up @@ -77,6 +78,13 @@ function Graph() {
setIsSorting(false);
return;
}
}else if (algo === "insertion") {
animation = insertionSort(array);
if (!Array.isArray(animation)) {
console.error("Invalid animation returned from sorting algorithm");
setIsSorting(false);
return;
}
}

setAnimations(animation);
Expand Down Expand Up @@ -159,7 +167,7 @@ function Graph() {
</div>
<input
type="range"
min="10"
min="20"
max="40"
onChange={(e) => generateArray(parseInt(e.target.value))}
defaultValue="20"
Expand Down Expand Up @@ -187,7 +195,7 @@ function Graph() {
{isSorting ? 'Stop' : 'Reset'}
</button>
</div>
<p className="note">Note: Currently only Bubble Sort, Quick Sort & Selection Sort is functioning. More sorting algorithms will be added soon.</p>
<p className="note">Note: Currently Merge Sort is not functioning. Will be added soon.</p>
</div>
<div className="section-container">
<div className="graph">
Expand Down

0 comments on commit 6d690b2

Please sign in to comment.