Docs
Quick Sort

Quick Sort

A hook for implementing quick sort.

About

The useQuickSort hook is a custom React hook that provides an implementation of the Quick Sort algorithm. It allows sorting arrays of primitive types (like numbers or strings) or complex objects with custom comparison logic. The hook efficiently sorts arrays in place and updates the sorted state dynamically.

Parameters

NameTypeDescription
arrayT[]The array to be sorted. This parameter is required when calling startSort.
comparator(a: T, b: T) => numberOptional. Custom comparison function to define how elements are compared (useful for objects).
onComplete(sortedArray: T[]) => voidOptional. Callback that gets triggered after the sorting completes with the sorted array.

Return Values

NameTypeDescription
sortedArrayT[]The array after it has been sorted. Initially, this is an empty array.
isSortingbooleanA boolean indicating if the sorting process is currently in progress.
startSort(array: T[], comparator?: (a: T, b: T) => number, onComplete?: (sortedArray: T[]) => void) => voidA function to initiate the Quick Sort process on the given array.
reset() => voidA function to reset the hook's state, clearing the sorted array and resetting sorting status.

Installation

Run the following command:

npx scriptkavi-hooks@latest add quick-sort

Usage

import { useQuickSort } from "@/hooks/quick-sort"

Basic Sorting an Array of Numbers

import React, { useState } from "react"
 
function QuickSortComponent() {
  const [array, setArray] = useState<number[]>([10, 5, 8, 3, 6, 1, 9])
  const { sortedArray, isSorting, startSort, reset } = useQuickSort<number>()
 
  return (
    <div>
      <h3>Original Array: {array.join(", ")}</h3>
      <h3>Sorted Array: {sortedArray.join(", ")}</h3>
 
      <button onClick={() => startSort(array)} disabled={isSorting}>
        {isSorting ? "Sorting..." : "Sort Numbers"}
      </button>
      <button onClick={reset} disabled={isSorting}>
        Reset
      </button>
    </div>
  )
}
 
export default QuickSortComponent

Sorting Objects with a Custom Comparator

You can sort an array of objects by providing a custom comparator function. Here is an example where we sort objects based on a property (e.g. age).

import React, { useState } from "react"
 
type Person = {
  name: string
  age: number
}
 
function ObjectQuickSortComponent() {
  const [people, setPeople] = useState<Person[]>([
    { name: "Alice", age: 25 },
    { name: "Bob", age: 30 },
    { name: "Charlie", age: 22 },
    { name: "David", age: 28 },
  ])
 
  const { sortedArray, isSorting, startSort, reset } = useQuickSort<Person>()
 
  const compareByAge = (a: Person, b: Person) => a.age - b.age
 
  return (
    <div>
      <h3>People:</h3>
      <ul>
        {people.map((person) => (
          <li key={person.name}>
            {person.name} - {person.age} years old
          </li>
        ))}
      </ul>
 
      <h3>Sorted People (by age):</h3>
      <ul>
        {sortedArray.map((person) => (
          <li key={person.name}>
            {person.name} - {person.age} years old
          </li>
        ))}
      </ul>
 
      <button
        onClick={() => startSort(people, compareByAge)}
        disabled={isSorting}
      >
        {isSorting ? "Sorting..." : "Sort by Age"}
      </button>
      <button onClick={reset} disabled={isSorting}>
        Reset
      </button>
    </div>
  )
}
 
export default ObjectQuickSortComponent

Sorting Completion Callback

You can pass an optional callback to startSort, which will be invoked when the sorting completes:

import React from "react"
 
const CallbackSortComponent = () => {
  const array = [3, 5, 1, 6, 4, 2]
  const { startSort, sortedArray, isSorting } = useQuickSort<number>()
 
  return (
    <div>
      <h3>Sorted Array: {sortedArray.join(", ")}</h3>
 
      <button
        onClick={() =>
          startSort(array, undefined, (sorted) => {
            console.log("Sorting complete!", sorted)
          })
        }
        disabled={isSorting}
      >
        {isSorting ? "Sorting..." : "Sort Array"}
      </button>
    </div>
  )
}
 
export default CallbackSortComponent

Resetting the Sorting State

The reset function can be called to reset the sorting state, clearing the sortedArray and resetting the isSorting flag:

import React from "react"
 
const ResetSortComponent = () => {
  const array = [9, 3, 5, 7, 1, 8]
  const { startSort, sortedArray, isSorting, reset } = useQuickSort<number>()
 
  return (
    <div>
      <h3>Sorted Array: {sortedArray.join(", ")}</h3>
 
      <button onClick={() => startSort(array)} disabled={isSorting}>
        {isSorting ? "Sorting..." : "Sort Array"}
      </button>
 
      <button onClick={reset} disabled={isSorting}>
        Reset
      </button>
    </div>
  )
}
 
export default ResetSortComponent

Custom Comparator Example

The useQuickSort hook supports custom comparators, allowing you to sort complex data types like objects. For instance, sorting people by their age can be done as follows:

const compareByAge = (a: Person, b: Person) => a.age - b.age

You can pass this comparator function as the second argument to startSort to sort the array based on a custom logic.

Considerations for Large Data Sets

  • Empty Arrays: The Quick Sort algorithm efficiently handles empty arrays by returning them immediately without processing.
  • Custom Comparison Logic: The hook is designed to handle both primitive types and complex objects by allowing a custom comparator function.
  • Recursive Nature: The Quick Sort algorithm is naturally recursive, and in extreme cases (e.g., large arrays with poor pivots), it might lead to deep recursion. For very large arrays, you might want to consider an iterative approach or tail recursion optimization.