提供一个贪心算法案例,Java代码
时间: 2023-06-09 13:04:16 浏览: 172
好的,这里给您提供一个贪心算法的经典案例——背包问题,以下是Java代码实现:
```java
public class KnapsackProblem {
public static int[] greedyKnapsack(int[] wt, int[] val, int capacity) {
int n = wt.length;
// calculating the value per unit weight
double[] ratio = new double[n];
for (int i = 0; i < n; i++) {
ratio[i] = (double) val[i] / wt[i];
}
// sorting the items in decreasing order of ratio (value per unit weight)
int[] index = new int[n];
for (int i = 0; i < n; i++) {
index[i] = i;
}
selectionSort(ratio, index);
// filling the knapsack using items in decreasing order of ratio (value per unit weight)
int[] result = new int[n];
int currentCapacity = 0;
for (int i = 0; i < n; i++) {
int itemIndex = index[i];
if (currentCapacity + wt[itemIndex] <= capacity) {
result[itemIndex] = 1;
currentCapacity += wt[itemIndex];
} else {
break;
}
}
return result;
}
// helper function for sorting the items based on ratio (value per unit weight)
public static void selectionSort(double[] arr, int[] index) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int maxIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] > arr[maxIndex]) {
maxIndex = j;
}
}
swap(arr, i, maxIndex);
swap(index, i, maxIndex);
}
}
// helper function for swapping two items in an array
public static void swap(double[] arr, int i, int j) {
double temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// helper function for swapping two items in an array
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int[] wt = {10, 20, 30};
int[] val = {60, 100, 120};
int capacity = 50;
int[] result = greedyKnapsack(wt, val, capacity);
System.out.println("Items in the knapsack:");
for (int i = 0; i < result.length; i++) {
if (result[i] == 1) {
System.out.println("Item " + (i + 1));
}
}
}
}
```
以上代码实现了一个贪心算法解决背包问题,该算法将物品按照单位重量的价值从大到小排序,然后依次将价值高的物品放入背包中,直到背包装满为止。
阅读全文