Data Structures and Algorithms: Thanh-Sach LE LTSACH@hcmut - Edu.vn March 31, 2020
Data Structures and Algorithms: Thanh-Sach LE LTSACH@hcmut - Edu.vn March 31, 2020
LAB #3
Thanh-Sach LE
[email protected]
Introduction
You study sorting algorithms this week. You learned how to sort arrays of data elements of specific data
type, for examples, sorting points in 2D-space by their x-coordinates. In the example, each data element
is an instance of class Point2D, and we hardcode the comparison between the x-coordinate of points.
Thereby, we have to re-write sorting algorithms for each type of data elements; it’s boring to do by such
the way.
How do we code the sorting algorithm in a general way and then we can use them for different type of
the data element? It is important to do in such the way for the data structures being studied in subsequent
lectures/chapters, for examples, list, tree, and graph of any data type.
Therefore, the objectives of this lab are as follows:
1. Practice generics programming in Java. You will be required to design sorting algorithms that are
able to work with any type of data elements.
2. Evaluate the executation time of sorting algorithms and then show it on console and create graphs
of the executation time (wrt the count of data elements) for each sorting algorithms.
1 java.util.Comparator
1
1 Point2D[] points = new Point2D[N]; //N: data count
2 //here: initialize data elements in ’points’
3 StraightInsertSort<Point2D> algorithm = new StraightInsertSort<>();
4 algorithm.sort(points, new PointComparator());
1 package sorting;
2 import java.util.Comparator;
3 public interface ISort<E> {
4 public void sort(E[] array, Comparator<E> comparator);
5 }
2
1 package sorting;
2 import java.util.Comparator;
3 public class StraightInsertionSort<E> implements ISort<E>{
4 @Override
5 public void sort(E[] array, Comparator<E> comparator){
6 int current, walker;
7 E temp;
8 current = 1;
9 while(current < array.length){
10 temp = array[current];
11 walker = current - 1;
12 while((walker >= 0) && comparator.compare(temp, array[walker])
< 0 ){
13 array[walker + 1] = array[walker]; //shift to right
14 walker -= 1;
15 }
16 array[walker + 1] = temp;
17 current += 1;
18 }
19 }
20 }
1 package geom;
2 import java.util.Comparator;
3 public class PointComparator implements Comparator<Point2D>{
4 @Override
5 public int compare(Point2D o1, Point2D o2) {
6 if(Math.abs(o1.getX() - o2.getX()) < 1e-7) return 0;
7 else if(o1.getX() < o2.getX()) return -1;
8 else return 1;
9 }
10 }
3
We can invoke method demo (in Figure 5) by creating a main entry point as shown in Figure 6. The
output is shown in Figure 7.
2 package sorting;
3 import geom.Point2D;
4 import geom.PointComparator;
5
11 //Print points
12 System.out.println("DEMO FOR INSERTION SORT:");
13 System.out.println(new String(new char[80]).replace(’\0’, ’=’));
14 System.out.println("Unsorted list points:");
15 System.out.println(new String(new char[80]).replace(’\0’, ’-’));
16 for(int idx=0; idx < N; idx++){
17 String line = String.format("%3d | %s", idx, points[idx]);
18 System.out.println(line);
19 }
20 //Sort: insertion sort
21 StraightInsertionSort<Point2D> sortAlg = new StraightInsertionSort
<>();
22 sortAlg.sort(points, new PointComparator());
23
24 //Print point
25 System.out.println("");
26 System.out.println("Sorted list of points (sorted by x-cooridinates
, ascending)");
27 System.out.println(new String(new char[80]).replace(’\0’, ’-’));
28 for(int idx=0; idx < N; idx++){
29 String line = String.format("%3d | %s", idx, points[idx]);
30 System.out.println(line);
31 }
32 }
33 }
1 package sorting;
2 import geom.*;
3 public class Sorting {
4 public static void main(String[] args) {
5 StraightInsertionSortDemo.demo();
6 }
7 }
4
1 DEMO FOR INSERTION SORT:
2 ==============================================================
3 Unsorted list points:
4 --------------------------------------------------------------
5 0 | P( 4.43, 4.95)
6 1 | P( -4.21, 18.91)
7 2 | P( 8.26, 18.07)
8 3 | P( 6.96, 17.94)
9 4 | P( 11.54, 18.92)
10 5 | P( -9.83, 17.27)
11 6 | P( 11.04, -0.95)
12 7 | P( 5.93, -7.67)
13 8 | P( 19.89, 17.16)
14 9 | P( -2.46, -5.54)
15
Question 1
Do the tasks below:
1. Using guideline in Lab1, define class Point2D in package geom.
2. Define class PointComparator as shown in Figure 4.
3. Define interface ISort as shown in Figure 2.
8. Do the analysis for the complexity of Straight Insertion Sort. Write the complexity Straight
Insertion Sort in a comment block placed preceding the method sort in Figure3, using the
format specified in Lab1.
5
2 Measuring the time of executation
In this lab, we try to measure the execution time of sorting algorithms. There are several ways to measure
time of execution in Java. In this Lab, we do the measurement with API System.nanoTime() (in nano
seconds), as shown in Figure 8. The difference between two calls to System.nanoTime() is the execution
time measured in nano-seconds; therefore, we need to divide for a million (1000000) to meaure time in
mili-seconds. In Line 22, we divide for (nExec ∗ 1000000) because we perform the sorting nExec times
for each of data size.
The question is Why do we execute nExec times for each data size? Yes, because the sorting time
of some algorithms depends on the order of data elements stored in the input array. Therefore, for each
data size (for-loop in Line 14), we try nExec times, each we generate an array of points and then do the
sorting.
1 package sorting;
2 import geom.Point2D;
3 import geom.PointComparator;
4
6
Question 2
Write a program to output the execution time of Straight insertion sort as shown Figure 9.
Guidelines:
• Create an instance of class StraightInsertionSort with element type Point2D.
• Invoke method timeit in SortingEval to get the execution time for each data size. The result
from timeit is array of Point2D; the x-coordinate is the data size (casting to double), and the
y-coordinate is the execution time. Remember, timeit is static, so you can call it without refering
to any object.
• Print the result using for-lop. Try String.format for formating the data.
3.2 Implementation
Question 3
Develop classes for other soring algorithms have been learnt. You are required to design your sorting
API to support code given in Figure 10 being compiled successfully.
Guidelines: Actually, the instructor has shared with you the source code of all algorithms studied
in the last lecture (see announcement in Blackboard). In the shared source code, the sorting algo-
rithms were hardcoded to work with only Point2D object. You can copy the ideas in preivous section
for Straight insertion sort to create your own implementation.
7
1 int[] num_segments = {1, 3, 7};
2 ISort[] algorithms = {
3 new StraightInsertionSort<Point2D>(),
4 new ShellSort<Point2D>(num_segments),
5 new StraightSelectionSort<Point2D>(),
6 new BubbleSort<Point2D>()
7 };
8
Question 4
The above sorting alorithms always sort the input data ascendingly. This question ask you to
modify the code developed above to allow programmers to select the sorting direction (ascending or
descending).
Guidelines:
• You must think your API supplied to programmers. A alot ways for doing a task like this, you
should select an easy and but efficent way.
– You can allow programmers to specify the sorting direction when they instantiate an sort-
ing object. Thereby, you have to add one more constructor to sorting class. You also need
to add one more data field to maintain the sorting direction. Sure, you need to add set-
ter/getter for it too.
• In method sort you need to test the value of the sorting direction (data field) and change the
comparison accordingly.
8
Question 5
The above section help you to sort points in 2D-space using the x-coordinate. This question ask you
to support the sorting of points ascendingly/descendingly with respect to their distance to the origin
of the space.
Guidelines:
• You need to create a new comparator for points, for example, a class with name
O2PointComparator; copy the idea from Figure 4.
• In method compare of O2PointComparator, you compute the distance from the origin (0, 0) to
two points, and then use these distances for comparison. The distance between two points you
have studied in high-school; you can ask Dr. Google if forget!
Question 6
The above section help you to sort points in 2D-space using the x-coordinate. This question ask you
to support the sorting of points ascendingly/descendingly with respect to their distance to the center
of mass of points stored in the array being sorted.
Guidelines:
• You need to create a new comparator for points, for example, a class with name
M2PointComparator; copy the idea from Figure 4. Different with previous question, you know
that the origin is at (0, 0). In this question, the comparator if created as O2PointComparator,
it does not know where the center of mass is.
– Therefore, you need to add a new constructor to M2PointComparator. This new contruc-
tor receives a point in 2D-space. Before instantiating an object of M2PointComparator,
you need to compute the center of mass for points stored in the input array, and then pass
the center to the constructor.
– You also add a data field to maintain the center in M2PointComparator; add setter/getter
if you want.
– You use the center stored in the data field (instead of the origin as in previous question)
to compute the distance between two points to the center.
– How to compute the center of mass? you consult Lab for this question.
• In method compare of M2PointComparator, you compute the distance from the center of mass
to two points, and then use these distances for comparison. The distance between two points
you have studied in high-school; you can ask Dr. Google if forget!
Question 7
Use the source code of the sample GUI-project shared with you and your modification in Lab2 to create
a diagram shown in Figure 11 for plotting the time of execution of sorting algorithms. Guidelines:
The code fragment for ploting the time of execution. You should think about where the code should
be.
9
Figure 11: Sorting time: StraightInsertionSort, ShellSort, StraightSelectionSort, BubbleSort
Question 8
As shown in Figure 11, ShellSort is best one, and BubbleSort the worst. Why? Write you explanation
to the above question to a block comment placed at the begining of each corresponding file.
Question 9
The source code of the sample GUI-project shared with you does not support features: (a) showing
the legend for each graph, and (b) add label for the x- and the y-axis, as you can see in Figure 11.
You are required to add such the features to your project.
10
1 int[] num_segments = {1, 3, 7};
2 ISort[] alg = {
3 new StraightInsertionSort<Point2D>(),
4 new ShellSort<Point2D>(num_segments),
5 new StraightSelectionSort<Point2D>(),
6 new BubbleSort<Point2D>()
7 };
8
9 Color[] color = {
10 Color.red, Color.green, Color.blue, Color.cyan
11 };
12 for(int aIdx=0; aIdx < alg.length; aIdx++){
13 Point2D[] time = SortingEval.timeit(alg[aIdx], 500, 500);
14 Graph graph = new Graph(time);
15 graph.setMode(Graph.GraphMode.SCATTER);
16 this.axis.addGraph(graph, color[aIdx], 1);
17 }
18
19 //update viewport
20 this.spaceMapping.updateLogViewPort(this.axis.getViewport());
21 this.repaint();
11