|
| 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