Skip to content

Commit

Permalink
Fix Jasmine tests and add expl comments to sort funcs
Browse files Browse the repository at this point in the history
Signed-off-by: Darko Draskovic <[email protected]>
  • Loading branch information
darkodraskovic committed Aug 14, 2022
1 parent e6fa392 commit a187ceb
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
5 changes: 3 additions & 2 deletions spec/sort.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,14 @@ describe("Function", function () {
});

let sortFuncs = [bubbleSort, selectionSort, insertionSort];
sortFuncs.forEach(func => {
for (let i = 0; i < sortFuncs.length; i++) {
const func = sortFuncs[i];
it(func.name + " which sorts numbers", function () {
let numbers = createNumbers();
func(numbers);
expect(numbers).toEqual(sorted);
});
});
}

it(mergeSort.name + " which sorts numbers", function () {
let numbers = createNumbers();
Expand Down
7 changes: 7 additions & 0 deletions src/algorithms/sort.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ function swapArrayElements(array, i1, i2) {
array[i2] = tmp;
}

// not used in real life; used to teach sorting
export function bubbleSort(array) {
for (let i = 0; i < array.length - 1; i++) {
for (let j = 1; j < array.length - i; j++) {
Expand All @@ -16,6 +17,7 @@ export function bubbleSort(array) {
}
}

// not used in real life; used to teach sorting
export function selectionSort(array) {
for (let i = 0; i < array.length - 1; i++) {
let smallestIdx = i;
Expand All @@ -42,6 +44,7 @@ function shiftRight(array, start, end) {
}
}

// use when only few items and with mostly sorted data
export function insertionSort(array) {
for (let i = 1; i < array.length; i++) {
if (array[i] < array[i - 1]) {
Expand All @@ -53,6 +56,8 @@ export function insertionSort(array) {
}
}

// use this if worst is probable: O(n log(n)) in worst
// however, space complexity is O(n)
export function mergeSort(array) {
if (array.length === 1) {
return array
Expand Down Expand Up @@ -86,6 +91,8 @@ export function merge(left, right) {
return array;
}

// O(n log(n)) in best and average
// space complexitiy is O(log(n)) (better than merge sort)
export function quickSort(array, left, right) {
if (left >= right) return;

Expand Down

0 comments on commit a187ceb

Please sign in to comment.