Skip to content

Commit ccf824c

Browse files
committed
[Manan] ADD:Sorting books prices in ascending order using merge sort
1 parent 9b50f11 commit ccf824c

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

SortingBookPrices.java

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
public class SortingBookPrices {
2+
3+
// Method to perform Merge Sort
4+
public static void mergeSort(int[] prices, int left, int right) {
5+
if (left < right) {
6+
// Find the middle index
7+
int mid = left + (right - left) / 2;
8+
9+
// Recursively sort the left half
10+
mergeSort(prices, left, mid);
11+
12+
// Recursively sort the right half
13+
mergeSort(prices, mid + 1, right);
14+
15+
// Merge the two sorted halves
16+
merge(prices, left, mid, right);
17+
}
18+
}
19+
20+
// Method to merge two sorted subarrays
21+
public static void merge(int[] prices, int left, int mid, int right) {
22+
// Sizes of the two subarrays
23+
int leftSize = mid - left + 1;
24+
int rightSize = right - mid;
25+
26+
// Temporary arrays to hold subarrays
27+
int[] leftArray = new int[leftSize];
28+
int[] rightArray = new int[rightSize];
29+
30+
// Copy data into temporary arrays
31+
for (int i = 0; i < leftSize; i++) {
32+
leftArray[i] = prices[left + i];
33+
}
34+
for (int j = 0; j < rightSize; j++) {
35+
rightArray[j] = prices[mid + 1 + j];
36+
}
37+
38+
// Merge the two subarrays
39+
int i = 0, j = 0, k = left;
40+
while (i < leftSize && j < rightSize) {
41+
if (leftArray[i] <= rightArray[j]) {
42+
prices[k] = leftArray[i];
43+
i++;
44+
} else {
45+
prices[k] = rightArray[j];
46+
j++;
47+
}
48+
k++;
49+
}
50+
51+
// Copy remaining elements of leftArray
52+
while (i < leftSize) {
53+
prices[k] = leftArray[i];
54+
i++;
55+
k++;
56+
}
57+
58+
// Copy remaining elements of rightArray
59+
while (j < rightSize) {
60+
prices[k] = rightArray[j];
61+
j++;
62+
k++;
63+
}
64+
}
65+
66+
// Method to print the array
67+
public static void printArray(int[] prices) {
68+
for (int price : prices) {
69+
System.out.print(price + " ");
70+
}
71+
System.out.println();
72+
}
73+
74+
// Main method
75+
public static void main(String[] args) {
76+
// Array representing book prices
77+
int[] bookPrices = {240, 110, 409, 149, 294, 144, 122};
78+
79+
System.out.println("Original Book Prices:");
80+
printArray(bookPrices);
81+
82+
// Sorting the book prices using Merge Sort
83+
mergeSort(bookPrices, 0, bookPrices.length - 1);
84+
85+
System.out.println("Sorted Book Prices :");
86+
printArray(bookPrices);
87+
}
88+
}

0 commit comments

Comments
 (0)