Skip to content

Commit

Permalink
Merge pull request #1595 from Subashree-selvaraj/librarysort
Browse files Browse the repository at this point in the history
Added library sort
  • Loading branch information
pankaj-bind authored Nov 4, 2024
2 parents 051214f + e639620 commit b13c61e
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
52 changes: 52 additions & 0 deletions Sorting Algorithms/Library Sort/Program.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#include <stdio.h>
#include <stdlib.h>

// 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;
}
23 changes: 23 additions & 0 deletions Sorting Algorithms/Library Sort/README.md
Original file line number Diff line number Diff line change
@@ -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.

0 comments on commit b13c61e

Please sign in to comment.