Skip to content

Commit 59b1e7d

Browse files
Merge branch 'main' into heap-sort
2 parents f9fed5d + 91aef43 commit 59b1e7d

File tree

6 files changed

+408
-17
lines changed

6 files changed

+408
-17
lines changed

C/algorithms/sorting/merge_sort.c

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
/*
2+
* Algorithm: Merge Sort
3+
* Description: Divide-and-conquer sorting algorithm that divides array into halves,
4+
* sorts them separately, and merges them back together
5+
* Time Complexity: O(n log n) for all cases
6+
* Space Complexity: O(n) for temporary arrays
7+
* Author: Abhijit
8+
* Date: October 2025
9+
* Hacktoberfest 2025
10+
*/
11+
12+
#include <stdio.h>
13+
#include <stdlib.h>
14+
15+
/**
16+
* Merges two subarrays of arr[]
17+
* First subarray is arr[left..mid]
18+
* Second subarray is arr[mid+1..right]
19+
*/
20+
void merge(int arr[], int left, int mid, int right) {
21+
int i, j, k;
22+
int n1 = mid - left + 1;
23+
int n2 = right - mid;
24+
25+
// Create temporary arrays
26+
int *leftArray = (int*)malloc(n1 * sizeof(int));
27+
int *rightArray = (int*)malloc(n2 * sizeof(int));
28+
29+
// Copy data to temporary arrays
30+
for (i = 0; i < n1; i++)
31+
leftArray[i] = arr[left + i];
32+
for (j = 0; j < n2; j++)
33+
rightArray[j] = arr[mid + 1 + j];
34+
35+
// Merge the temporary arrays back into arr[left..right]
36+
i = 0; // Initial index of first subarray
37+
j = 0; // Initial index of second subarray
38+
k = left; // Initial index of merged subarray
39+
40+
while (i < n1 && j < n2) {
41+
if (leftArray[i] <= rightArray[j]) {
42+
arr[k] = leftArray[i];
43+
i++;
44+
} else {
45+
arr[k] = rightArray[j];
46+
j++;
47+
}
48+
k++;
49+
}
50+
51+
// Copy the remaining elements of leftArray[], if any
52+
while (i < n1) {
53+
arr[k] = leftArray[i];
54+
i++;
55+
k++;
56+
}
57+
58+
// Copy the remaining elements of rightArray[], if any
59+
while (j < n2) {
60+
arr[k] = rightArray[j];
61+
j++;
62+
k++;
63+
}
64+
65+
// Free the temporary arrays
66+
free(leftArray);
67+
free(rightArray);
68+
}
69+
70+
/**
71+
* Main function that sorts arr[left..right] using merge sort
72+
*/
73+
void mergeSort(int arr[], int left, int right) {
74+
if (left < right) {
75+
// Find the middle point to divide the array into two halves
76+
int mid = left + (right - left) / 2;
77+
78+
// Sort first and second halves
79+
mergeSort(arr, left, mid);
80+
mergeSort(arr, mid + 1, right);
81+
82+
// Merge the sorted halves
83+
merge(arr, left, mid, right);
84+
}
85+
}
86+
87+
/**
88+
* Utility function to print array elements
89+
*/
90+
void printArray(int arr[], int n) {
91+
for (int i = 0; i < n; i++) {
92+
printf("%d ", arr[i]);
93+
}
94+
printf("\n");
95+
}
96+
97+
int main() {
98+
int n;
99+
100+
// Prompt the user for the number of elements
101+
printf("Enter the number of elements: ");
102+
scanf("%d", &n);
103+
104+
if (n <= 0) {
105+
printf("Invalid input! Number of elements must be positive.\n");
106+
return 1;
107+
}
108+
109+
int arr[n]; // Declare an array of size n
110+
111+
// Read the elements from the user
112+
printf("Enter %d numbers: ", n);
113+
for (int i = 0; i < n; i++) {
114+
scanf("%d", &arr[i]);
115+
}
116+
117+
printf("\nOriginal array: ");
118+
printArray(arr, n);
119+
120+
mergeSort(arr, 0, n - 1);
121+
122+
printf("Sorted array: ");
123+
printArray(arr, n);
124+
125+
printf("\nAlgorithm Information:\n");
126+
printf("- Time Complexity: O(n log n) for all cases\n");
127+
printf("- Space Complexity: O(n) for temporary arrays\n");
128+
printf("- Stable sorting algorithm\n");
129+
printf("- Divide-and-conquer approach\n");
130+
131+
return 0;
132+
}

HALL_OF_FAME.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,7 @@ Welcome to the **Hall of Fame**! This page celebrates all the amazing contributo
339339

340340
| Metric | Count | Growth |
341341
|--------|-------|--------|
342-
| 👥 **Total Contributors** | 77+ Amazing Developers | 📈 +Growing Daily |
342+
| 👥 **Total Contributors** | 81+ Amazing Developers | 📈 +Growing Daily |
343343
| 📝 **Total Commits** | 200+ Quality Commits | 📈 +Active Development |
344344
| 🔥 **Algorithms Implemented** | 100+ Implementations | 📈 +Weekly Additions |
345345
| 🌍 **Languages Supported** | 4 (C, C++, Java, Python) | 📈 +Expanding |
@@ -410,7 +410,7 @@ Welcome to the **Hall of Fame**! This page celebrates all the amazing contributo
410410

411411
#### 🙏 **Special Thanks to All Our 2024 Contributors**
412412

413-
We extend our heartfelt gratitude to all **77+ contributors** who made this repository possible in 2024:
413+
We extend our heartfelt gratitude to all **81+ contributors** who made this repository possible in 2024:
414414

415415
**🏆 Top Contributors (5+ commits):**
416416
- [@Pradeepsingh61](https://github.com/Pradeepsingh61) - 130 contributions 👑 **Project Founder**
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import java.util.Arrays;
2+
3+
public class HeapSort {
4+
static void heapify(int arr[], int n, int i) {
5+
int largest = i;
6+
int left = 2 * i + 1;
7+
int right = 2 * i + 2;
8+
9+
if (left < n && arr[left] > arr[largest])
10+
largest = left;
11+
12+
if (right < n && arr[right] > arr[largest])
13+
largest = right;
14+
15+
if (largest != i) {
16+
int temp = arr[i];
17+
arr[i] = arr[largest];
18+
arr[largest] = temp;
19+
heapify(arr, n, largest);
20+
}
21+
}
22+
23+
static void heapSort(int arr[]) {
24+
int n = arr.length;
25+
26+
for (int i = n / 2 - 1; i >= 0; i--)
27+
heapify(arr, n, i);
28+
29+
for (int i = n - 1; i >= 0; i--) {
30+
int temp = arr[0];
31+
arr[0] = arr[i];
32+
arr[i] = temp;
33+
heapify(arr, i, 0);
34+
}
35+
}
36+
37+
public static void main(String[] args) {
38+
int arr[] = {12, 11, 13, 5, 6, 7};
39+
System.out.println("Original array: " + Arrays.toString(arr));
40+
heapSort(arr);
41+
System.out.println("Sorted array: " + Arrays.toString(arr));
42+
}
43+
}
Lines changed: 101 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,119 @@
1+
"""
2+
Heap Sort Algorithm
3+
Time Complexity: O(n log n) in all cases
4+
Space Complexity: O(1) - sorts in place
5+
Author: Karanjot Singh
6+
Date: October 2025
7+
Hacktoberfest 2025
8+
"""
9+
110
def heapify(arr, n, i):
11+
"""
12+
Heapify subtree rooted at index i
13+
14+
Args:
15+
arr: Array to heapify
16+
n: Size of heap
17+
i: Root index of subtree
18+
"""
219
largest = i
3-
l = 2 * i + 1
4-
r = 2 * i + 2
20+
left = 2 * i + 1
21+
right = 2 * i + 2
22+
23+
# Check if left child exists and is greater than root
24+
if left < n and arr[left] > arr[largest]:
25+
largest = left
526

6-
if l < n and arr[l] > arr[largest]:
7-
largest = l
8-
if r < n and arr[r] > arr[largest]:
9-
largest = r
27+
# Check if right child exists and is greater than largest so far
28+
if right < n and arr[right] > arr[largest]:
29+
largest = right
30+
31+
# If largest is not root, swap and continue heapifying
1032
if largest != i:
1133
arr[i], arr[largest] = arr[largest], arr[i]
1234
heapify(arr, n, largest)
1335

14-
def heapSort(arr):
36+
def heap_sort(arr):
37+
"""
38+
Heap sort implementation
39+
40+
Steps:
41+
1. Build max heap from array
42+
2. Extract elements one by one from heap
43+
3. Place extracted element at the end
44+
45+
Args:
46+
arr: List to sort (modified in place)
47+
"""
1548
n = len(arr)
1649

50+
# Build max heap
51+
# Start from last non-leaf node and heapify each node
1752
for i in range(n // 2 - 1, -1, -1):
1853
heapify(arr, n, i)
1954

55+
# Extract elements from heap one by one
2056
for i in range(n - 1, 0, -1):
57+
# Move current root to end
2158
arr[0], arr[i] = arr[i], arr[0]
59+
60+
# Heapify the reduced heap
2261
heapify(arr, i, 0)
2362

24-
# Taking user input
25-
input_str = input("Enter numbers separated by space: ")
26-
arr = list(map(int, input_str.split()))
2763

28-
heapSort(arr)
64+
def heap_sort_copy(arr):
65+
"""
66+
Heap sort that returns sorted copy
67+
68+
Args:
69+
arr: List to sort
70+
71+
Returns:
72+
Sorted copy of the list
73+
"""
74+
arr_copy = arr.copy()
75+
heap_sort(arr_copy)
76+
return arr_copy
77+
78+
79+
# Test cases
80+
if __name__ == "__main__":
81+
print("=== Heap Sort Algorithm ===\n")
82+
83+
# Test case 1: Random array
84+
test1 = [12, 11, 13, 5, 6, 7]
85+
print(f"Original array: {test1}")
86+
sorted1 = heap_sort_copy(test1)
87+
print(f"Sorted array: {sorted1}")
88+
89+
# Test case 2: Already sorted
90+
test2 = [1, 2, 3, 4, 5]
91+
print(f"\nOriginal array: {test2}")
92+
sorted2 = heap_sort_copy(test2)
93+
print(f"Sorted array: {sorted2}")
94+
95+
# Test case 3: Reverse sorted
96+
test3 = [10, 8, 6, 4, 2]
97+
print(f"\nOriginal array: {test3}")
98+
sorted3 = heap_sort_copy(test3)
99+
print(f"Sorted array: {sorted3}")
100+
101+
# Test case 4: Array with duplicates
102+
test4 = [4, 10, 3, 5, 1, 3, 10]
103+
print(f"\nOriginal array: {test4}")
104+
sorted4 = heap_sort_copy(test4)
105+
print(f"Sorted array: {sorted4}")
106+
107+
# Test case 5: Large array
108+
test5 = [64, 34, 25, 12, 22, 11, 90, 88, 45, 50, 23, 36]
109+
print(f"\nOriginal array: {test5}")
110+
sorted5 = heap_sort_copy(test5)
111+
print(f"Sorted array: {sorted5}")
112+
113+
# Test case 6: Single element
114+
test6 = [42]
115+
print(f"\nOriginal array: {test6}")
116+
sorted6 = heap_sort_copy(test6)
117+
print(f"Sorted array: {sorted6}")
29118

30-
print("Sorted array is")
31-
for i in arr:
32-
print(i, end=' ')
119+
print("\n✅ All test cases completed!")

0 commit comments

Comments
 (0)