0% found this document useful (0 votes)
6 views1 page

JavaScript Sorting Algorithms Guide

The document provides JavaScript implementations for three sorting algorithms: Insertion Sort, Heap Sort, and Quick Sort. Each algorithm is defined in a function that takes an array as input and returns the sorted array. The code snippets include necessary helper functions for Heap Sort to maintain the heap property.

Uploaded by

hv014300
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

JavaScript Sorting Algorithms Guide

The document provides JavaScript implementations for three sorting algorithms: Insertion Sort, Heap Sort, and Quick Sort. Each algorithm is defined in a function that takes an array as input and returns the sorted array. The code snippets include necessary helper functions for Heap Sort to maintain the heap property.

Uploaded by

hv014300
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Insertion Sort (JavaScript)

function insertionSort(arr) {
for (let i = 1; i < [Link]; i++) {
let key = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
return arr;
}

Heap Sort (JavaScript)


function heapSort(arr) {
let n = [Link];
for (let i = [Link](n / 2) - 1; i >= 0; i--) {
heapify(arr, n, i);
}
for (let i = n - 1; i > 0; i--) {
[arr[0], arr[i]] = [arr[i], arr[0]];
heapify(arr, i, 0);
}
return arr;
}
function heapify(arr, n, i) {
let largest = i;
let left = 2 * i + 1;
let right = 2 * i + 2;
if (left < n && arr[left] > arr[largest]) largest = left;
if (right < n && arr[right] > arr[largest]) largest = right;
if (largest !== i) {
[arr[i], arr[largest]] = [arr[largest], arr[i]];
heapify(arr, n, largest);
}
}

Quick Sort (JavaScript)


function quickSort(arr) {
if ([Link] <= 1) return arr;
let pivot = arr[[Link] - 1];
let left = [];
let right = [];
for (let i = 0; i < [Link] - 1; i++) {
if (arr[i] < pivot) [Link](arr[i]);
else [Link](arr[i]);
}
return [...quickSort(left), pivot, ...quickSort(right)];
}

You might also like