You are on page 1of 3

1.

Here,
Item n=5 & maximum weight capacity m = 16
X1 X2 X3 X4 X5
Item 1 2 3 4 5
Value 15 30 40 20 25
Weight 2 4 6 8 10

For fraction its 0<=x<=1

Step 1:
Value / Weight = P
P 7.5 7.5 6.6 2.5 2.5

Step 2:
Including highest (value/weight) first
X X1 X2 X3 X4 X5
1 1 1 1/2 0

*Taking item one (X1) full so 16-2=14


*Taking item X2 full so 14-4=10
*Taking item X3 full so 10-6=4
*Taking item X4’s ½ so 4-4=0

Step 3:
Maximum profit is = 1*15+1*30+1*40+1/2*20=95
Step 4:
Verifying the weight = 1*2+1*4+1*6+1/2*8+0*10=16

1
2.
#include <iostream>

using namespace std;

void countSort(int array[], int size) {

// The size of count must be at least the (max+1) but we cannot assign declare it as int count(max+1) in
C++ as it does not support dynamic memory allocation. So, its size is provided statically

int output[10];

int count[10];

int max = array[0];

// Find the largest element of the array

for (int i = 1; i < size; i++) {

if (array[i] > max)

max = array[i];

// Initialize count array with all zeros

for (int i = 0; i <= max; ++i) {

count[i] = 0;

// Store the count of each element

for (int i = 0; i < size; i++) {

count[array[i]]++;

// Store the cummulative count of each array

for (int i = 1; i <= max; i++) {

count[i] += count[i - 1];

// Find the index of each element of the original array in count array, and place the elements in output
array

for (int i = size - 1; i >= 0; i--) {

2
output[count[array[i]] - 1] = array[i];

count[array[i]]--;

// Copy the sorted elements into original array

for (int i = 0; i < size; i++) {

array[i] = output[i];

// Function to print an array

void printArray(int array[], int size) {

for (int i = 0; i < size; i++)

cout << array[i] << " ";

cout << endl; }

// Driver code

int main() {

int array[] = {4, 2, 2, 8, 3, 3, 1};

int n = sizeof(array) / sizeof(array[0]);

countSort(array, n);

printArray(array, n);

You might also like