From ed0d23c4211c26fc9626c19947c5328f1d228e5a Mon Sep 17 00:00:00 2001 From: Yash Tariyal <77398467+YashTariyal@users.noreply.github.com> Date: Sun, 13 Oct 2024 11:10:47 +0530 Subject: [PATCH] feat: created bucket_sort.ts --- sorts/bucket_sort.ts | 70 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 sorts/bucket_sort.ts diff --git a/sorts/bucket_sort.ts b/sorts/bucket_sort.ts new file mode 100644 index 00000000..a50a4763 --- /dev/null +++ b/sorts/bucket_sort.ts @@ -0,0 +1,70 @@ +// Import the prompt-sync package +const prompt = require('prompt-sync')(); + +// Function to sort individual buckets using insertion sort +function insertionSort(bucket: number[]): number[] { + for (let i = 1; i < bucket.length; i++) { + let key = bucket[i]; + let j = i - 1; + while (j >= 0 && bucket[j] > key) { + bucket[j + 1] = bucket[j]; + j--; + } + bucket[j + 1] = key; + } + return bucket; +} + +// Function to sort arr[] using bucket sort +function bucketSort(arr: number[]): number[] { + const n = arr.length; + + // 1) Create n empty buckets + let buckets: number[][] = new Array(n); + for (let i = 0; i < n; i++) { + buckets[i] = []; + } + + // 2) Put array elements in different buckets + for (let i = 0; i < n; i++) { + const bi = Math.floor(n * arr[i]); // Index in the bucket array + buckets[bi].push(arr[i]); + } + + // 3) Sort individual buckets using insertion sort + for (let i = 0; i < n; i++) { + buckets[i] = insertionSort(buckets[i]); + } + + // 4) Concatenate all buckets into the original array + let index = 0; + for (let i = 0; i < n; i++) { + for (let j = 0; j < buckets[i].length; j++) { + arr[index++] = buckets[i][j]; + } + } + + return arr; +} + +// Function to get user input and handle sorting +function main() { + // Take the number of elements from the user + const n = parseInt(prompt('Enter the number of elements: ')); + + // Initialize an array and take user input for each element + let arr: number[] = []; + for (let i = 0; i < n; i++) { + const element = parseFloat(prompt(`Enter element ${i + 1}: `)); + arr.push(element); + } + + // Sort the array using bucket sort + const sortedArr = bucketSort(arr); + + // Print the sorted array + console.log('Sorted array is:', sortedArr); +} + +// Run the main function to start the program +main(); pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy