Skip to content

Commit e7db4e1

Browse files
committed
[Manan] ADD:Sorting product prices in ascending order using quick sort
1 parent ccf824c commit e7db4e1

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

SortingProductPrices.java

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
public class SortingProductPrices {
2+
3+
// Method to sort product prices using Quick Sort
4+
public static void quickSort(int[] prices, int left, int right) {
5+
if (left < right) {
6+
int partitionIndex = partition(prices, left, right);
7+
quickSort(prices, left, partitionIndex - 1);
8+
quickSort(prices, partitionIndex + 1, right);
9+
}
10+
}
11+
12+
// Partition method to place pivot at correct position
13+
private static int partition(int[] prices, int left, int right) {
14+
int pivot = prices[right]; // Choosing the last element as the pivot
15+
int i = left - 1; // Pointer for smaller elements
16+
17+
for (int j = left; j < right; j++) {
18+
if (prices[j] < pivot) {
19+
i++;
20+
swap(prices, i, j);
21+
}
22+
}
23+
swap(prices, i + 1, right); // Place pivot at correct position
24+
return i + 1;
25+
}
26+
27+
// Method to swap two elements
28+
private static void swap(int[] prices, int i, int j) {
29+
int temp = prices[i];
30+
prices[i] = prices[j];
31+
prices[j] = temp;
32+
}
33+
34+
// Main method to test sorting
35+
public static void main(String[] args) {
36+
int[] productPrices = {490, 433, 782, 223, 873, 289};
37+
38+
// Sorting the prices
39+
quickSort(productPrices, 0, productPrices.length - 1);
40+
41+
// Display sorted prices
42+
System.out.println("Sorted Product Prices:");
43+
for (int price : productPrices) {
44+
System.out.print(price + " ");
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)