Lab 2 Ex6. The k-th largest number (5 marks)

Lab 2 Ex6. The k-th largest number (5 marks)

You cannot submit for this problem because the homework's deadline is due.

Ex6. The \(k\)-th largest number (10 marks)

Read a row vector of real numbers and a positive integer \(k\) from user input, and output the \(k\)-th largest number in the vector. The vector is non-empty and \(k\) is guaranteed to be less than or equal to the length of the vector.

There are many ways to implement this. Given below is one possible approach for your reference:

  1. Get the maximum in the vector along with its index.
  2. Remove it from the vector.
  3. Repeat the steps above \(k\) times.

Caveat: MATLAB does provide you with a method to remove elements from vectors. However, due to the way vectors are implemented by computers, this kind of operations are actually not computer-friendly. You will learn more about this in VE280. To make your algorithm more efficient, consider using NaN. Hint: What does max() do with NaN?

Note: If you are into algorithms, we recommend you to search for an algorithm called quickselect, which has average case optimal performance (\(O(n)\)) on this problem. Using this algorithm to solve this problem is completely optional. There will be large test cases, but they are only worth few marks. Remember that as long as you get (70 marks) out of (110 marks) you will receive full points for this lab. Only take this little challenge if you are interested and have some basic knowledge in algorithms!

Sample Test Cases

Input:

[12 7 45 2 19 37]
1

Output:

    45

Input:

[12 7 45 2 19 37]
4

Output:

    12

Lab2 Exercises

Not Claimed
Status
Finished
Problems
6
Open Since
2022-05-26 18:00
DDL
2022-05-27 23:59
Extension
24.0 hour(s)