Skip to content

[Feat] : Added Quick Sort #35

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

Merged
merged 4 commits into from
Oct 8, 2022
Merged
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
74 changes: 74 additions & 0 deletions Sorts/QuickSort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* @function quickSort
* @description is an algorithm based on divide and conquer approach in which an array is split into sub-arrays and these sub arrays are recursively sorted to get final array
* @see [Quick Sort](https://www.javatpoint.com/quick-sort)
* @example QuickSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8]
*/

export const partition = (
array: number[],
left: number = 0,
right: number = array.length - 1
) => {
const pivot = array[Math.floor((right + left) / 2)];
let i = left;
let j = right;

while (i <= j) {
while (array[i] < pivot) {
i++;
}

while (array[j] > pivot) {
j--;
}

if (i <= j) {
[array[i], array[j]] = [array[j], array[i]];
i++;
j--;
}
}

return i;
};

/**
* Quicksort implementation
*
* @param {number[]} array
* @param {number} [left=0]
* @param {number} [right=array.length - 1]
* @returns {number[]}
* @complexity_analysis
* Space complexity - O(nlogn)
* Time complexity
* Best case - O(nlogn)
* When pivot element lies in the middle of the list
* Worst case - O(n^2)
* When pivot element lies on the extreme ends
* Average case - O(nlogn)
* When the above two cases are not met
*/

export const QuickSort = (
array: number[],
left: number = 0,
right: number = array.length - 1
) => {
let index;

if (array.length > 1) {
index = partition(array, left, right);

if (left < index - 1) {
QuickSort(array, left, index - 1);
}

if (index < right) {
QuickSort(array, index, right);
}
}

return array;
};
15 changes: 15 additions & 0 deletions Sorts/test/QuickSort.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { QuickSort } from "../QuickSort";

describe("Quick Sort", () => {
it("should return the correct value for average case", () => {
expect(QuickSort([1, 4, 2, 5, 9, 6, 3, 8, 10, 7])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
});

it("should return the correct value for worst case", () => {
expect(QuickSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
});

it("should return the correct value for best case", () => {
expect(QuickSort([1, 4, 2, 9, 5, 7, 3, 8, 10, 6])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
});
});