Skip to content

Instantly share code, notes, and snippets.

@OzzyTheGiant
Last active June 4, 2021 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OzzyTheGiant/02a82b33a158fc2a14a14e2dd65cd391 to your computer and use it in GitHub Desktop.
Save OzzyTheGiant/02a82b33a158fc2a14a14e2dd65cd391 to your computer and use it in GitHub Desktop.
Sorting Algorithms
const numbers = [20, 48, 7, 12, 17, 5, 69, 88, 192, 54, 45];
function quickSort(array, left, right){
if (right - left < 1) return;
let pivot = right
let index = left
while (pivot - index > 0) {
if (array[index] > array[pivot]) {
const temp = array[pivot]
array[pivot] = array[index]
if (pivot - index === 1) {
array[index] = temp
} else {
array[index] = array[pivot - 1]
array[pivot - 1] = temp
}
pivot--
} else {
index++
}
}
quickSort(array, left, pivot - 1)
quickSort(array, pivot + 1, right)
}
//Select first and last index as 2nd and 3rd parameters
quickSort(numbers, 0, numbers.length - 1);
console.log(numbers);
function mergeSort(array) {
if (array.length === 1) {
return array
}
// Split Array in into right and left
const length = array.length;
const middle = Math.floor(length / 2)
const left = array.slice(0, middle)
const right = array.slice(middle)
return merge(
mergeSort(left),
mergeSort(right)
)
}
function merge(left, right) {
const result = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length &&
rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
result.push(left[leftIndex]);
leftIndex++;
} else {
result.push(right[rightIndex]);
rightIndex++
}
}
// console.log(left, right)
return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex));
}
const answer = mergeSort(numbers);
console.log(answer);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment