Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

quicksor and mergesort in javascript #164

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Sorting Algorithms/mergesort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
var unsortedArr = [340, 1, 3, 3, 76, 23, 4, 12, 122, 7642, 646];
function merge(leftArr, rightArr) {
var sortedArr = [];
while (leftArr.length && rightArr.length) {
if (leftArr[0] <= rightArr[0]) {
sortedArr.push(leftArr[0]);
leftArr = leftArr.slice(1);
} else {
sortedArr.push(rightArr[0]);
rightArr = rightArr.slice(1);
}
}
while (leftArr.length) sortedArr.push(leftArr.shift());
while (rightArr.length) sortedArr.push(rightArr.shift());
return sortedArr;
}
function mergesort(arr) {
if (arr.length < 2) {
return arr;
} else {
var midpoint = parseInt(arr.length / 2);
var leftArr = arr.slice(0, midpoint);
var rightArr = arr.slice(midpoint, arr.length);
return merge(mergesort(leftArr), mergesort(rightArr));
}
}
console.log("This should be the sorted array!");
console.log(mergesort(unsortedArr));
44 changes: 44 additions & 0 deletions Sorting Algorithms/quicksort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
var items = [5, 3, 7, 6, 2, 9];
function swap(items, leftIndex, rightIndex) {
var temp = items[leftIndex];
items[leftIndex] = items[rightIndex];
items[rightIndex] = temp;
}
function partition(items, left, right) {
var pivot = items[Math.floor((right + left) / 2)], //middle element
i = left, //left pointer
j = right; //right pointer
while (i <= j) {
while (items[i] < pivot) {
i++;
}
while (items[j] > pivot) {
j--;
}
if (i <= j) {
swap(items, i, j); //sawpping two elements
i++;
j--;
}
}
return i;
}

function quickSort(items, left, right) {
var index;
if (items.length > 1) {
index = partition(items, left, right); //index returned from partition
if (left < index - 1) {
//more elements on the left side of the pivot
quickSort(items, left, index - 1);
}
if (index < right) {
//more elements on the right side of the pivot
quickSort(items, index, right);
}
}
return items;
}
// first call to quick sort
var sortedArray = quickSort(items, 0, items.length - 1);
console.log(sortedArray); //prints [2,3,5,6,7,9]