IBDP Computer Science B2.4 Programming algorithms HL Paper 2 - New Syllabus
Question
int. [2]The ProductManagement class has the main method and other methods to generate the information required:
public class ProductManagement {
private Product[] allProducts = new Product[25];
public void sortProducts() // sort in descending order of prodSale {
// code missing
}
} // end of ProductManagement classsortProducts() to sort the allProducts[] array in descending order of prodSale.You must make use of the selection sort algorithm. [6]
Most-appropriate topic code
▶️ Answer/Explanation
(a) (i)
For the correct answer:
A primitive data type is a predefined, fundamental, or basic data type provided directly by a programming language. Primitive data types are basic building blocks used to represent simple values.
(a) (ii)
For the correct answer:
One advantage is memory efficiency. Primitive data types such as int generally require less memory than objects, making them efficient when working with large datasets or in memory-constrained environments.
Another valid advantage is that primitive data types can provide faster access and manipulation because they are stored directly and can be processed efficiently by the CPU.
(b)
For the correct answer, the selection sort algorithm should be used to arrange the products in descending order of prodSale.
public void sortProducts()
{
int n = allProducts.length;
for (int i = 0; i < n - 1; i++)
{
int maxIndex = i;
for (int j = i + 1; j < n; j++)
{
if (allProducts[j].getProdSale() >
allProducts[maxIndex].getProdSale())
{
maxIndex = j;
}
}
// Swap the elements
Product temp = allProducts[maxIndex];
allProducts[maxIndex] = allProducts[i];
allProducts[i] = temp;
}
}How the selection sort works:
- The outer loop moves through each position in the array.
maxIndexis initially set to the current position.- The inner loop searches the remaining unsorted elements for the product with the highest
prodSale. getProdSale()is used to compare the sales values.- The product with the highest sales value is selected.
- The selected product is swapped with the product at the current position.
Repeating this process places the products in descending order of prodSale.
Marking points covered:
- Correct outer loop
- Correct inner loop
- Correct initialization and updating of
maxIndex - Correct comparison of
prodSalevalues - Use of
getProdSale() - Correct attempt to swap and correct swap
Note: If selection sort is not used but another correct sorting algorithm is used, the supplied markscheme allows a maximum of 4 marks.
