From e639620a797a836a36a4aed5fc5aab8d6194d934 Mon Sep 17 00:00:00 2001 From: Subashree-selvaraj Date: Sun, 3 Nov 2024 15:56:01 +0530 Subject: [PATCH] Added library sort --- Sorting Algorithms/Library Sort/Program.c | 52 +++++++++++++++++++++++ Sorting Algorithms/Library Sort/README.md | 23 ++++++++++ 2 files changed, 75 insertions(+) create mode 100644 Sorting Algorithms/Library Sort/Program.c create mode 100644 Sorting Algorithms/Library Sort/README.md diff --git a/Sorting Algorithms/Library Sort/Program.c b/Sorting Algorithms/Library Sort/Program.c new file mode 100644 index 00000000..988af729 --- /dev/null +++ b/Sorting Algorithms/Library Sort/Program.c @@ -0,0 +1,52 @@ +#include +#include + +// Function to insert an element into the sorted array with gaps +void insert(int arr[], int *size, int element) { + int i = *size - 1; + while (i >= 0 && arr[i] > element) { + arr[i + 1] = arr[i]; + i--; + } + arr[i + 1] = element; + (*size)++; +} + +// Function to perform library sort +void library_sort(int arr[], int n) { + int *sorted = (int *)malloc(2 * n * sizeof(int)); + int size = 0; + + for (int i = 0; i < n; i++) { + insert(sorted, &size, arr[i]); + } + + for (int i = 0; i < n; i++) { + arr[i] = sorted[i]; + } + + free(sorted); +} + +// Function to print array +void print_array(int arr[], int n) { + for (int i = 0; i < n; i++) { + printf("%d ", arr[i]); + } + printf("\n"); +} + +int main() { + int arr[] = {78, 650, 100, 21, 23, 12, 90, 0}; + int n = sizeof(arr) / sizeof(arr[0]); + + printf("Original array:\n"); + print_array(arr, n); + + library_sort(arr, n); + + printf("Sorted array:\n"); + print_array(arr, n); + + return 0; +} \ No newline at end of file diff --git a/Sorting Algorithms/Library Sort/README.md b/Sorting Algorithms/Library Sort/README.md new file mode 100644 index 00000000..517477c0 --- /dev/null +++ b/Sorting Algorithms/Library Sort/README.md @@ -0,0 +1,23 @@ +# Library Sort + +## Description + +Library Sort is a sorting algorithm that is a variant of insertion sort. It maintains a sorted array with gaps to allow for efficient insertion of new elements. This algorithm is also known as gapped insertion sort. + +## Problem Definition + +Given: +- An array `arr` of `n` elements. + +Objectives: +- Sort an array in ascending order using library sort. + +## Algorithm Overview + +1. **Initialize**: Start with an empty sorted array with gaps. +2. **Insert**: For each element in the input array, find the correct position in the sorted array and insert it, shifting elements as necessary. +3. **Rebalance**: Periodically rebalance the array to maintain gaps for efficient insertion. + +## Time Complexity + +The time complexity of Library Sort is `O(n log n)` on average, but it can degrade to `O(n^2)` in the worst case if the gaps are not managed properly. It is efficient for datasets where insertions are frequent and the array needs to remain sorted. \ No newline at end of file