You are on page 1of 2

Homework week 9

Algorithms - Part 2

1. Given a list of real numbers, your task is to implement a ‘quick’ sorting algorithm to
order these numbers increasingly.

Input: The input consists of n in the first line and n real numbers separated by spaces in
the next n lines.
Output: The sorted numbers and two numbers are separated by a space character.
Input Output
6 122358
352218
Tips: You can use the merge sort algorithm to solve this exercise. Read carefully the lecture 8 to
understand the idea and pseudo code of the algorithm.
2. Given an integer number X and a list A of n natural numbers that are the ages of n
students, your task is to find a group of students such that the sum of their ages is equal to
X.

Input: The input consists of n and X in the first line, and n natural numbers in the second
line separated by spaces.
Output: Write ‘YES’ if existed, otherwise ‘NO’
Input Output
6 10 YES
256217
Tips: The idea to sovle the problem is that we select sequentially numbers and put to a set A satisfying
that sumation of A's elements less than X. In case, there is not any element selected, we remove
the last selected element in the set A and repeate the above process. To implement this idea, a
recursive algorithm is suitable to solve.
3. Given n objects each has a weight w and a value v, your task is to select a number of
objects with the largest sum of values conditioned that the sum of their weights is not
greater than X.

Input: The input consists of numbers n and X in the first line, and n pairs of natural numbers
(weight and value) in the next n lines.
Output: The largest sum of values identified.
Input Output
5 10 12
11
22
33
99
8 10
Tips: Using a dynamic programing algorithm as the following pseudo code:
// Input:
// Values (stored in array v)
// Weights (stored in array w)
// Number of distinct items (n)
// Knapsack capacity (W)
// NOTE: The array "v" and array "w" are assumed to store all
relevant values starting at index 1.
for j from 0 to W do: m[0, j] := 0
for i from 1 to n do:
for j from 0 to W do:
if w[i] > j then: m[i, j] := m[i-1, j]
else: m[i, j] := max(m[i-1, j], m[i-1, j-w[i]] + v[i])

You might also like