Consider you have the following integer array: int[5] array = {5, 4, 3, 2, 1}; W
ID: 3804993 • Letter: C
Question
Consider you have the following integer array: int[5] array = {5, 4, 3, 2, 1}; Write a program that shifts the content of the array to the right, i.e. the array would become array = {1, 5, 4, 3, 2}; Write the definition of an abstract class Shape that define two abstract methods getArea() and getPerimeter() returning, respectively the area and the perimeter of that Shape. Then write the definition and implementation of a derived classes of class Shape: class Rectangle. Rectangle class defines two private side integer fields and it overrides methods getArea() and getPerimeter() of the Shape class. What is the complexity of this following code fragment? Give the details how you got the result. int A[n][n]; For(int I = 0; i x; A[i][j] = x;} int suntLine = 0; For(int k=0;kExplanation / Answer
This is the java code of your program:
Q1:Main1.java
import java.util.Arrays;
public class main1 {
public static void shift( int [] arr )
{
int last = arr[arr.length-1];
for( int i =arr.length-2; i >= 0 ; i-- )
{
arr[i+1] = arr [i];
}
arr[0] = last;
System.out.print(" After Shifting array: " + Arrays.toString(arr) );
}
public static void main(String[] argv) throws Exception {
int[] arr = { 5,4,3,2,1 };
System.out.println(" Before Shifting array: " + Arrays.toString(arr));
shift(arr);
}
}
Q2:
Shape.java
public abstract class Shape {
private String id;
public Shape (String id)
{this.id = id;}
public abstract double getArea();
public abstract double getPerimeter();
}
Rectangle.java
public class Rectangle extends Shape {
private double width, height;
public Rectangle (String name, double width, double height)
{
super(name);
width = width;
height = height;
}
@Override
public double getArea()
{
return width*height;
}
public double getWidth()
{
return width;
}
public double getHeight()
{
return height;
}
public void setWidth(double width) {
this.width = width;
}
public void setHeight(double height) {
this.height = height;
}
@Override
public double getPerimeter() {
return 2 * (width+height);
}
}
Q3:
The complexity of the program is O(n3).
Because every single loop of n number's complexity is O(n),
Every loop inside loop's complexity is O(n2),
here in the code first for loop is loop inside loop so complexity is O(n2),
and last loop's complexity is O(n),so Total complexity is O(n2)+O(n) = O(n3).
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.