Skip to content

Commit b13c61e

Browse files
authored
Merge pull request #1595 from Subashree-selvaraj/librarysort
Added library sort
2 parents 051214f + e639620 commit b13c61e

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
// Function to insert an element into the sorted array with gaps
5+
void insert(int arr[], int *size, int element) {
6+
int i = *size - 1;
7+
while (i >= 0 && arr[i] > element) {
8+
arr[i + 1] = arr[i];
9+
i--;
10+
}
11+
arr[i + 1] = element;
12+
(*size)++;
13+
}
14+
15+
// Function to perform library sort
16+
void library_sort(int arr[], int n) {
17+
int *sorted = (int *)malloc(2 * n * sizeof(int));
18+
int size = 0;
19+
20+
for (int i = 0; i < n; i++) {
21+
insert(sorted, &size, arr[i]);
22+
}
23+
24+
for (int i = 0; i < n; i++) {
25+
arr[i] = sorted[i];
26+
}
27+
28+
free(sorted);
29+
}
30+
31+
// Function to print array
32+
void print_array(int arr[], int n) {
33+
for (int i = 0; i < n; i++) {
34+
printf("%d ", arr[i]);
35+
}
36+
printf("\n");
37+
}
38+
39+
int main() {
40+
int arr[] = {78, 650, 100, 21, 23, 12, 90, 0};
41+
int n = sizeof(arr) / sizeof(arr[0]);
42+
43+
printf("Original array:\n");
44+
print_array(arr, n);
45+
46+
library_sort(arr, n);
47+
48+
printf("Sorted array:\n");
49+
print_array(arr, n);
50+
51+
return 0;
52+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Library Sort
2+
3+
## Description
4+
5+
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.
6+
7+
## Problem Definition
8+
9+
Given:
10+
- An array `arr` of `n` elements.
11+
12+
Objectives:
13+
- Sort an array in ascending order using library sort.
14+
15+
## Algorithm Overview
16+
17+
1. **Initialize**: Start with an empty sorted array with gaps.
18+
2. **Insert**: For each element in the input array, find the correct position in the sorted array and insert it, shifting elements as necessary.
19+
3. **Rebalance**: Periodically rebalance the array to maintain gaps for efficient insertion.
20+
21+
## Time Complexity
22+
23+
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 commit comments

Comments
 (0)