Skip to content

Commit

Permalink
Created Quick_Sort.ts (jainaman224#3031)
Browse files Browse the repository at this point in the history
* Created Quick_Sort.ts

Added quicksort implementation in TypeScript jainaman224#2131

* Updated Quick_Sort.ts

Added 4 space indentation
  • Loading branch information
dj373 authored Jun 4, 2020
1 parent 0357d28 commit 8780882
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions Quick_Sort/Quick_Sort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Description: Function to perform the Quick Sort algorithm on an array of numbers
// Expected Output: returns the sorted array

// Helper function to get the Pivoting Element Index
function 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--;
}

// Swap values based on indices
if (i <= j)
{
[array[i], array[j]] = [array[j], array[i]];
i++;
j--;
}
}

return i;
}


// Function that uses recursive definition for quick sort implementation
function 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;
}

// I/P
var arr = [6, 5, 4, 3, 2, 1];

console.log("Before sorting ",arr)
var res = quickSort(arr)

console.log("After sorting ",res)
// O/P
// 1,2,3,4,5,6

0 comments on commit 8780882

Please sign in to comment.