Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

College of Computing and Informatics

Computer Programming - II
CS141

Assignment 2
Deadline: Sunday 04/04/2021 @ 23:59
[Total Mark for this Assignment is 5]

Student Details:
Name: ID:

CRN:

Instructions:

You must submit two separate copies (one Word file and one PDF file) using the Assignment Template on
Blackboard via the allocated folder. These files must not be in compressed format.
It is your responsibility to check and make sure that you have uploaded both the correct files.
Zero mark will be given if you try to bypass the SafeAssign (e.g. misspell words, remove spaces between words,
hide characters, use different character sets or languages other than English or any kind of manipulation).
Email submission will not be accepted.
You are advised to make your work clear and well-presented. This includes filling your information on the cover
page.
You must use this template, failing which will result in zero mark.
You MUST show all your work, and text must not be converted into an image, unless specified otherwise by the
question.
Late submission will result in ZERO mark.
The work should be your own, copying from students or other resources will result in ZERO mark.
Use Times New Roman font for all your answers.
Pg. 1 Question FourQuestion Four

Learning 2 Marks
Outcome(s): Question One
CLO3
Use the following method to generate an array (arr1) of 5000 randomly
Instructors: generated elements.
Design and
implement public static int[] RandomArrayGenerator(int n)
{
programs using
int[] Array = new int[n];
object oriented Random r = new Random();
programming for(int i=0;i<n;i++)
concepts such as {
encapsulation, Array[i] = r.nextInt(1000);
inheritance, }
return Array;
polymorphism,
}
abstract classes
and methods.

Now the method will generate 5000 random element

[Note that by using nextInt(100) you will generate an integer between 0 and
100.]

a. Use insertion sort to sort arr1.


b. Use RandomArrayGenerator again to create arr2 containing 5000
randomly generated element.
c. Use the static sort methods of Java's Arrays class to sort arr2.
d. Time each of the methods so that you can make a comparison of the
efficiency. You can create longs and store the system time to know
when the method starts and ends. You can then take the difference run
time in milliseconds.
long startTime = System.currentTimeMillis();
Pg. 2 Question FourQuestion Four

//call sort method here


long endTime = System.currentTimeMillis();

solution:

//Sorting.java

import java.util.Arrays;
import java.util.Random;

public class Sorting {


public static int[] RandomArrayGenerator(int n) {
int[] Array = new int[n];
Random r = new Random();
for (int i = 0; i < n; i++) {
Array[i] = r.nextInt(1000);
}
return Array;
}

// method to sort an array of given size, using insertion sort algorithm


public static void insertionSort(int array[]) {
// looping from i=0 to i=n-1
for (int i = 0; i < array.length; i++) {
// fetching value at index i as key (value to insert at proper
position)
int key = array[i];
// setting i-1 as j
int j = i - 1;
// looping as long as j>=0 and array[j]>key
while (j >= 0 && array[j] > key) {
// shifting element at j one place right
array[j + 1] = array[j];
// decrementing j
j--;
}
// adding key at index j+1
array[j + 1] = key;
}
Pg. 3 Question FourQuestion Four

public static void main(String[] args) {


// creating an array of 5000 random integers
int[] arr1 = RandomArrayGenerator(5000);
// recording start time
long start = System.currentTimeMillis();
// sorting using the method we defined
insertionSort(arr1);
// recording end time, and calculating time needed
long stop = System.currentTimeMillis();
long time1 = stop - start;

// creating another array of same size


int[] arr2 = RandomArrayGenerator(5000);
start = System.currentTimeMillis();
// using Arrays.sort method to sort
Arrays.sort(arr2);
stop = System.currentTimeMillis();
// recording time needed
long time2 = stop - start;

// displaying both times


System.out.println("Time needed to sort arr1 using insertionSort method:
" + time1 + " ms");
System.out.println("Time needed to sort arr2 using Arrays.sort() method:
" + time2 + " ms");

// observation: Arrays.sort() runs way more faster than the method we


defined,
// this is because Arrays.sort() uses quicksort algorithm, which is way
// efficient and faster than insertionSort.
}
}

 
output
Pg. 4 Question FourQuestion Four

Time needed to sort arr1 using insertionSort method: 23 ms


Time needed to sort arr2 using Arrays.sort() method: 4 ms
Pg. 5 Question FourQuestion Four

1 Mark
Learning
Outcome(s): Question Two
CLO2

Instructors:
Suppose you have the following array: {11, 22, 33, 44, 55, 66, 77}. Write a java
Apply recursion program to find the sum of elements of the array recursively.
concept in
programming. Solution:

class Test {
    static int arr[] = { 1, 2, 3, 4, 5 };
  
    // Return sum of elements in A[0..N-1]
    // using recursion.
    static int findSum(int A[], int N)
    {
        if (N <= 0)
            return 0;
        return (findSum(A, N - 1) + A[N - 1]);
    }
  
    // Driver method
    public static void main(String[] args)
    {
        System.out.println(findSum(arr, arr.length));
    }
}
Pg. 6 Question FourQuestion Four

0.5 Marks
Learning
Outcome(s): Question Three
CLO4

Instructors:
Suppose a program builds and manipulates a linked list:
Demonstrate
dynamic data What two special nodes would the program typically keep track of? Describe
structures such
two common uses for the null reference in the node of the linked lists.
us linked lists,
stacks and Answer:
queues, and
binary trees. Step1:

A linked List is a linear data structure where the elements are not stored in a contiguous
location and every element is a separate object with a data part and address part .

Here the two special nodes that the program keep the track of are 

1st Node: store the content of a data.

2nd Node: Keep the address of the next node.


Pg. 7 Question FourQuestion Four

Implementations: There are usually two forms of linked list:

 Without a dummy head (refer to the top singly linked list in the following diagram), or
 With a dummy head (bottom one). Dummy headers are often used because they help
with the implementation.
Pg. 8 Question FourQuestion Four

1.5 Marks
Learning
Outcome(s): Question Four
CLO4

Instructors:
Consider the following Java Code:
Demonstrate
What is the output when this code is executed?
dynamic data
structures such import java.util.LinkedList;
us linked lists, import java.util.ListIterator;
class Main {
stacks and
public static void main(String[] args) {
queues, and LinkedList<String> myLList = new LinkedList<String>();
binary trees. myLList.addFirst("Ali");
myLList.addFirst("Omar");
myLList.addLast("Sara");
ListIterator<String> myiterator = myLList.listIterator();
myiterator.next();
myiterator.next();
myiterator.add("Reem");
myiterator.previous();
myiterator.add("Ahmad");
myiterator.add("Khaled");
myiterator.previous();
myiterator.remove();
System.out.println(myLList);
myiterator.next();
myiterator.next();
System.out.println("MyList Backward iteration :");
while(myiterator.hasPrevious())
System.out.println(myiterator.previous());
System.out.println("---------------------");
}
}

Solution
This will be the result
Pg. 9 Question FourQuestion Four

[Omar, Ali, Ahmad, Reem, Sara]


MyList Backward iteration :
Sara
Reem
Ahmad
Ali
Omar
---------------------

You might also like