- Notifications
You must be signed in to change notification settings - Fork 379
Expand file tree
/
Copy pathAdvancedSortingAlgorithms.java
More file actions
Latest commit
308 lines (269 loc) · 9.52 KB
/
Copy pathAdvancedSortingAlgorithms.java
File metadata and controls
308 lines (269 loc) · 9.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/**
* Advanced Sorting Algorithms Collection
*
* This class implements various efficient sorting algorithms including:
* - Merge Sort (O(n log n) time, O(n) space)
* - Quick Sort (O(n log n) average, O(n²) worst case)
* - Heap Sort (O(n log n) time, O(1) space)
* - Counting Sort (O(n + k) time for integers)
*
* Each algorithm is thoroughly documented with time/space complexity analysis.
*
* @author Hacktoberfest Contributor
* @version 1.0
*/
publicclassAdvancedSortingAlgorithms {
/**
* Merge Sort - Divide and Conquer Algorithm
* Time Complexity: O(n log n) in all cases
* Space Complexity: O(n) for temporary arrays
*
* @param arr Array to be sorted
* @param left Starting index
* @param right Ending index
*/
publicstaticvoidmergeSort(int[] arr, intleft, intright) {
if (left < right) {
// Find the middle point to divide array into two halves
intmid = left + (right - left) / 2;
// Recursively sort first and second halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
// Merge the sorted halves
merge(arr, left, mid, right);
}
}
/**
* Helper method to merge two sorted subarrays
*
* @param arr Main array
* @param left Starting index of left subarray
* @param mid Ending index of left subarray
* @param right Ending index of right subarray
*/
privatestaticvoidmerge(int[] arr, intleft, intmid, intright) {
// Create temporary arrays for left and right subarrays
int[] leftArray = newint[mid - left + 1];
int[] rightArray = newint[right - mid];
// Copy data to temporary arrays
System.arraycopy(arr, left, leftArray, 0, leftArray.length);
System.arraycopy(arr, mid + 1, rightArray, 0, rightArray.length);
// Merge the temporary arrays back into arr[left..right]
inti = 0, j = 0, k = left;
while (i < leftArray.length && j < rightArray.length) {
if (leftArray[i] <= rightArray[j]) {
arr[k++] = leftArray[i++];
} else {
arr[k++] = rightArray[j++];
}
}
// Copy remaining elements
while (i < leftArray.length) {
arr[k++] = leftArray[i++];
}
while (j < rightArray.length) {
arr[k++] = rightArray[j++];
}
}
/**
* Quick Sort - Partition-based Algorithm
* Time Complexity: O(n log n) average, O(n²) worst case
* Space Complexity: O(log n) due to recursion stack
*
* @param arr Array to be sorted
* @param low Starting index
* @param high Ending index
*/
publicstaticvoidquickSort(int[] arr, intlow, inthigh) {
if (low < high) {
// Partition the array and get pivot index
intpivotIndex = partition(arr, low, high);
// Recursively sort elements before and after partition
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
/**
* Partition method for Quick Sort using last element as pivot
*
* @param arr Array to partition
* @param low Starting index
* @param high Ending index
* @return Index of pivot after partitioning
*/
privatestaticintpartition(int[] arr, intlow, inthigh) {
intpivot = arr[high]; // Choose last element as pivot
inti = low - 1; // Index of smaller element
for (intj = low; j < high; j++) {
// If current element is smaller than or equal to pivot
if (arr[j] <= pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high); // Place pivot in correct position
returni + 1;
}
/**
* Heap Sort - Tree-based sorting algorithm
* Time Complexity: O(n log n) in all cases
* Space Complexity: O(1) - sorts in place
*
* @param arr Array to be sorted
*/
publicstaticvoidheapSort(int[] arr) {
intn = arr.length;
// Build max heap (rearrange array)
for (inti = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
// Extract elements from heap one by one
for (inti = n - 1; i > 0; i--) {
// Move current root to end
swap(arr, 0, i);
// Call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
/**
* Heapify a subtree rooted at given index
*
* @param arr Array representing the heap
* @param n Size of heap
* @param i Root index of subtree
*/
privatestaticvoidheapify(int[] arr, intn, inti) {
intlargest = i; // Initialize largest as root
intleft = 2 * i + 1; // Left child
intright = 2 * i + 2; // Right child
// If left child is larger than root
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
// If right child is larger than largest so far
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
// If largest is not root
if (largest != i) {
swap(arr, i, largest);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
/**
* Counting Sort - Non-comparison based sorting
* Time Complexity: O(n + k) where k is the range of input
* Space Complexity: O(k) for counting array
*
* @param arr Array to be sorted (assumes non-negative integers)
* @return New sorted array
*/
publicstaticint[] countingSort(int[] arr) {
if (arr.length == 0) returnarr;
// Find the maximum element to determine range
intmax = findMax(arr);
// Create counting array
int[] count = newint[max + 1];
int[] output = newint[arr.length];
// Count occurrences of each element
for (intnum : arr) {
count[num]++;
}
// Transform count array to store actual positions
for (inti = 1; i <= max; i++) {
count[i] += count[i - 1];
}
// Build output array in reverse order to maintain stability
for (inti = arr.length - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
returnoutput;
}
/**
* Utility method to find maximum element in array
*/
privatestaticintfindMax(int[] arr) {
intmax = arr[0];
for (inti = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
returnmax;
}
/**
* Utility method to swap two elements in array
*/
privatestaticvoidswap(int[] arr, inti, intj) {
inttemp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/**
* Utility method to print array
*/
privatestaticvoidprintArray(int[] arr, Stringlabel) {
System.out.print(label + ": ");
for (intvalue : arr) {
System.out.print(value + " ");
}
System.out.println();
}
/**
* Utility method to copy array
*/
privatestaticint[] copyArray(int[] original) {
int[] copy = newint[original.length];
System.arraycopy(original, 0, copy, 0, original.length);
returncopy;
}
/**
* Main method to demonstrate all sorting algorithms
*/
publicstaticvoidmain(String[] args) {
System.out.println("=== Advanced Sorting Algorithms Demo ===\n");
// Test data
int[] originalArray = {64, 34, 25, 12, 22, 11, 90, 5, 77, 30};
System.out.println("Original Array:");
printArray(originalArray, "Unsorted");
System.out.println();
// Test Merge Sort
System.out.println("--- Merge Sort ---");
int[] mergeArray = copyArray(originalArray);
longstartTime = System.nanoTime();
mergeSort(mergeArray, 0, mergeArray.length - 1);
longendTime = System.nanoTime();
printArray(mergeArray, "Merge Sort Result");
System.out.println("Time taken: " + (endTime - startTime) + " nanoseconds");
System.out.println();
// Test Quick Sort
System.out.println("--- Quick Sort ---");
int[] quickArray = copyArray(originalArray);
startTime = System.nanoTime();
quickSort(quickArray, 0, quickArray.length - 1);
endTime = System.nanoTime();
printArray(quickArray, "Quick Sort Result");
System.out.println("Time taken: " + (endTime - startTime) + " nanoseconds");
System.out.println();
// Test Heap Sort
System.out.println("--- Heap Sort ---");
int[] heapArray = copyArray(originalArray);
startTime = System.nanoTime();
heapSort(heapArray);
endTime = System.nanoTime();
printArray(heapArray, "Heap Sort Result");
System.out.println("Time taken: " + (endTime - startTime) + " nanoseconds");
System.out.println();
// Test Counting Sort
System.out.println("--- Counting Sort ---");
int[] countArray = copyArray(originalArray);
startTime = System.nanoTime();
int[] countResult = countingSort(countArray);
endTime = System.nanoTime();
printArray(countResult, "Counting Sort Result");
System.out.println("Time taken: " + (endTime - startTime) + " nanoseconds");
System.out.println("\n=== All algorithms completed successfully! ===");
}
}