24
Tirgul no. 6 Tirgul no. 6 Topics covered Topics covered : : Constructors – types of constructors Constructors – types of constructors Two-dimensional and Multi-dimensional arrays Two-dimensional and Multi-dimensional arrays in java. in java. Sorting an array of numbers using the Sorting an array of numbers using the BubbleSort algorithm, pseudo-code and java BubbleSort algorithm, pseudo-code and java implementation. implementation. Complexity analysis (running time) of the Complexity analysis (running time) of the BubbleSort algorithm. BubbleSort algorithm.

Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

  • View
    218

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Tirgul no. 6Tirgul no. 6

Topics coveredTopics covered:: Constructors – types of constructorsConstructors – types of constructors

Two-dimensional and Multi-dimensional arrays in java.Two-dimensional and Multi-dimensional arrays in java.

Sorting an array of numbers using the BubbleSort algorithm, Sorting an array of numbers using the BubbleSort algorithm, pseudo-code and java implementation.pseudo-code and java implementation.

Complexity analysis (running time) of the BubbleSort Complexity analysis (running time) of the BubbleSort algorithm.algorithm.

Page 2: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Constructors revisited:Constructors revisited:

There are 3 basic types of constructors that can be defined for There are 3 basic types of constructors that can be defined for a class:a class:1)1) Default constructor Default constructor – a constructor that receives no parameters. If no – a constructor that receives no parameters. If no

constructors are defined – the compiler automatically creates an empty constructors are defined – the compiler automatically creates an empty default constructor.default constructor.

2)2) Insertion constructorInsertion constructor – any constructor that receives some parameters – any constructor that receives some parameters which are used to initialize the data members of the object created.which are used to initialize the data members of the object created.

3)3) Copy constructorCopy constructor – a constructor which receives a ref to an object of – a constructor which receives a ref to an object of the same class – and uses it to copy the ‘internal state’ (all data the same class – and uses it to copy the ‘internal state’ (all data members) of that object to the newly created object. This constructor members) of that object to the newly created object. This constructor creates a new copy of the object it receives as a parameter.creates a new copy of the object it receives as a parameter.

Page 3: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Constructor example:Constructor example:public class NumberedRectangle {

private int serialNumber;private Point p1; //lower left corner.private Point p2 // upper right corner.

//default constructorpublic NumberedRectangle(){

serialNumber= 0;p1= new Point(0,0);p2= new Point(1,1);

}

//insertion constructorpublic NumberedRectangle(int serialNumber, Point p1, Point p2){

this.serialNumber= serialNumber;this.p1= new Point(p1);this.p2= new Point(p2);

}

Page 4: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Defining constructors (cont.)Defining constructors (cont.)

//class NumberedRectangle continued.

public NumberedRectangle(NumberedRectangle other){

this.serialNumber= other.serialNumber;

this.p1= new Point(other.p1);

this.p2= new Point(other.p2);

}

//other methods…

} //end of class

Note that since the ref passed to the copy constructor is a ref to an object of the same type which is created – the new object has direct access to the other objects’ data members!

Page 5: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Constructor overloadingConstructor overloading

In java a class can have more than one constructor defintion. In java a class can have more than one constructor defintion. This is called This is called Constructor OverloadingConstructor Overloading and is a special case of and is a special case of Method overloading Method overloading (will be addressed in future lessons)(will be addressed in future lessons)

The compiler knows which constructor to call by looking at the The compiler knows which constructor to call by looking at the parameters that are passed to the constructor, when it is called. parameters that are passed to the constructor, when it is called. Therefore – the constructors must differ in their parameter Therefore – the constructors must differ in their parameter lists: they can have a different number of parameters, or lists: they can have a different number of parameters, or different kinds of parameters.different kinds of parameters.

Page 6: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Two-Dimensional Arrays: Two-Dimensional Arrays: declaration and initializationdeclaration and initialization A two dimensional array – is actually an array of arrays.A two dimensional array – is actually an array of arrays. Declaration:Declaration:

boolean[ ][ ] table;boolean[ ][ ] table;

Table is a reference to a 2-dimensional array of booleans which is uninitialized.Table is a reference to a 2-dimensional array of booleans which is uninitialized.

Initialization: Initialization:

option I:option I:

table= new boolean[10][5];table= new boolean[10][5];

table now refers to an array of 10 boolean arrays, each with 5 boolean table now refers to an array of 10 boolean arrays, each with 5 boolean values. This can be thought of as a table with 10 rows and 5 columns.values. This can be thought of as a table with 10 rows and 5 columns.

Page 7: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Two-Dimensional Arrays: Two-Dimensional Arrays: declaration and initializationdeclaration and initialization

Option II:Option II:

table= new boolean[3][ ];table= new boolean[3][ ];

table[0] = new boolean[3];table[0] = new boolean[3];

table[1]= new boolean[10];table[1]= new boolean[10];

table[2]= new boolean[2];table[2]= new boolean[2];

This way table now refers to an array of 3 boolean arrays, each This way table now refers to an array of 3 boolean arrays, each with a different size. Note – each cell in the array must be with a different size. Note – each cell in the array must be initialized separately – if they are not all initialized using initialized separately – if they are not all initialized using option I.option I.

Page 8: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

2-dim arrays with different 2-dim arrays with different lengths:lengths:

Example:Example:

int intArray2D[ ][ ] = new int[5][ ]; for(int i=0; i<intArray2D.length; i++) intArray2D[i] = new int[i+1]; What we have now is:What we have now is:

intArray2D[0]intArray2D[1]intArray2D[2]intArray2D[3]intArray2D[4]

Page 9: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Accessing a 2-dim array:Accessing a 2-dim array:

Accesing the arrays is done using indices:Accesing the arrays is done using indices:table[0][1]= true; table[0][1]= true;

Or:Or:

if( table[i][j] )if( table[i][j] )

//some code//some code

Page 10: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

int[][] table = new table [10][10];for (int i=0; i<10; i++) for (int j=0; j<10; j++)

table[i][j] = i * j; System.out.println(table[4][3]);System.out.println(table[2][1]);

Multiplication Table ExampleMultiplication Table Example

Page 11: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Multidimensional ArraysMultidimensional Arrays

In java we can define arrays of any dimension. This can be In java we can define arrays of any dimension. This can be thought of as an array of arrays of arrays… thought of as an array of arrays of arrays…

Each array can have a different size which will be denoted by Each array can have a different size which will be denoted by its its lengthlength field. field.

Example:Example:

int[][][] counts= new int[2][2][ ];int[][][] counts= new int[2][2][ ];

counts[0][1]= new int[10];counts[0][1]= new int[10];

counts[1][1]= new int[20];counts[1][1]= new int[20];

……

counts[0][0][0]= 100; counts[0][0][0]= 100;

Page 12: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Multi Dimensional ArraysMulti Dimensional Arrays

Two equivalent ways to create a 2x3 array of int:

Separate creation and initialization:

int intArray2D[][] = new int[2][3]; intArray2D[0][0]=1; intArray2D[0][1]=2; intArray2D[0][2]=3; intArray2D[1][0]=4; intArray2D[1][1]=5; intArray2D[1][2]=6;

Declaration and initialization (size is implied by initialization):

int intArray2D[][] = {{1,2,3}, {4,5,6}};

Page 13: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Arrays of objectsArrays of objects

Create a 2x2 array of strings, initially all entries are “null”:

String stringArray2D[][] = new String[2][2];

Create a 2x2 array of strings which are initialized:

String stringArray2D[][] = {{new String("a"),new String("aa")}, {new String("b"), new String("bb")}};

Page 14: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Permutation MatricesPermutation Matrices

Definition:

An NxN matrix is a permutation matrix if in each row and column of the matrix there is only one entry with the value ‘1’ and all other values are ‘0’.

Examples: 1 0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 1 0 1 0 0 0 0 1 0

Page 15: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Permutation Matrix ClassPermutation Matrix Class

public class PermMat { private int data[][]; public PermMat(int data[][]) { this.data = new int[data.length][data[0].length]; if(isPerm(data)) { for(int i=0; i<data.length; i++)

System.arraycopy(data[i],0,this.data[i],0,data[i].length); } else

setIdentity(); }

Page 16: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Permutation Matrix Class (cont.)Permutation Matrix Class (cont.)private boolean isPerm(int data[][]) {

int i,j,numOnes; //check the rows for(i=0; i<data.length; i++) { numOnes = 0; for(j=0; j<data[0].length; j++) {

if(data[i][j] != 0) { if(((data[i][j] == 1) && (numOnes==1)) || (data[i][j] != 1)) return false; else numOnes++;}

} if(numOnes == 0)

return false; } cont on next slide...

Page 17: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Permutation Matrix Class (cont.)Permutation Matrix Class (cont.)

//check the columns for(j=0; j<data[0].length; j++) { numOnes = 0; for(i=0; i<data.length; i++) {

if(data[i][j] != 0) { if(((data[i][j] == 1) && (numOnes==1)) || (data[i][j] != 1)) return false; else numOnes++;}

} if(numOnes == 0)

return false; } return true; }

Page 18: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Sorting an array of numbers- Sorting an array of numbers- Buble SortBuble Sort Sorting is a basic task used in many different contexts. Sorting is a basic task used in many different contexts.

There are many different algorithms to sort a list of numbers, There are many different algorithms to sort a list of numbers, (or any other objects which can be ordered). (or any other objects which can be ordered).

We present a simple naïve sorting algorithm called BubbleSort.We present a simple naïve sorting algorithm called BubbleSort.

Basic idea: each time “bubble” largest element left in the array Basic idea: each time “bubble” largest element left in the array to its place at the end of the array, until all values are to its place at the end of the array, until all values are positioned in their “correct” place.positioned in their “correct” place.

Page 19: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

BubbleSort – PseudoCode:BubbleSort – PseudoCode:• Notice different notation: this is just intended to be readable for any Notice different notation: this is just intended to be readable for any

programmer in ANY language!programmer in ANY language!//assume A is an array of numbers of size n.//assume A is an array of numbers of size n.BubbleSort(A){BubbleSort(A){

(1) for i=1 to n do(1) for i=1 to n do (1.1) for j=1 to n-1 do(1.1) for j=1 to n-1 do (1.1.1) if (A[j] > A[j+1] ) then(1.1.1) if (A[j] > A[j+1] ) then

(1.1.1.1) swap(A,j,j+1);(1.1.1.1) swap(A,j,j+1);} }

//swap two values in the array A in indices i, and j.//swap two values in the array A in indices i, and j.swap(A,i,j){swap(A,i,j){

(1) temp (1) temp A[i]; A[i];(2) A[i] (2) A[i] A[j]; A[j];(3) A[j] (3) A[j] temp; temp;

}}

Page 20: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

BubbleSort: java code:BubbleSort: java code:

public void bubbleSort(int[] array){public void bubbleSort(int[] array){

for(int i=0; i<array.length; i++)for(int i=0; i<array.length; i++)

for(int j=0; j<array.length-1; j++)for(int j=0; j<array.length-1; j++)

if(array[j] > array[j+1]){if(array[j] > array[j+1]){

int temp= array[j];int temp= array[j];

array[j]= array[j+1];array[j]= array[j+1];

array[j+1]= temp;array[j+1]= temp;

}}

}}

Page 21: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

BubbleSort – complexity BubbleSort – complexity analysisanalysis

We want to measure how efficient is the algorithm.We want to measure how efficient is the algorithm. You have seen in class that the standard way of doing this is by You have seen in class that the standard way of doing this is by

analyzing the number of operations that the algorithm performs analyzing the number of operations that the algorithm performs for a given input of size n.for a given input of size n.

we measure the running time of the algorithms as a function of we measure the running time of the algorithms as a function of the input size n.the input size n.

In our case – the input size is : the Array’s size!In our case – the input size is : the Array’s size!

BubbleSort running time: for an array of size n how many BubbleSort running time: for an array of size n how many times will we evaluate the times will we evaluate the ifif statement (and decide if to swap statement (and decide if to swap or not to swap 2 values)?or not to swap 2 values)?

Page 22: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

BubbleSort – complexity BubbleSort – complexity analysisanalysis

Anlysis:Anlysis:

outer loop: n times, outer loop: n times,

each time runs inner loop n-1 iterations: each time runs inner loop n-1 iterations:

total istotal is: n(n-1) : n(n-1) if if evaluations.evaluations.

We write: T(n)= n(n-1)= O(nWe write: T(n)= n(n-1)= O(n22) using the “Big O” notation ) using the “Big O” notation shown in class. shown in class.

QuestionQuestion: can we improve the BubbleSort algorithm shown : can we improve the BubbleSort algorithm shown here?here?

Page 23: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

BubbleSort – improved version:BubbleSort – improved version: Answer: notice that after the first iteration of the outer loop the Answer: notice that after the first iteration of the outer loop the

largest element in the array is “bubbled” to the last place in the largest element in the array is “bubbled” to the last place in the array – and we don’t need to compare any of the other numbers array – and we don’t need to compare any of the other numbers to it again – it will never be moved from that location!to it again – it will never be moved from that location!

public void bubbleSort(int[] array){public void bubbleSort(int[] array){for(int i=0; i<array.length; i++)for(int i=0; i<array.length; i++) for(int j=0; for(int j=0; j<array.length-(i+1)j<array.length-(i+1); j++); j++) if(array[j] > array[j+1]){if(array[j] > array[j+1]){ int temp= array[j];int temp= array[j];

array[j]= array[j+1];array[j]= array[j+1];array[j+1]= temp;array[j+1]= temp;

}}}}

Page 24: Tirgul no. 6 Topics covered : b Constructors – types of constructors b Two-dimensional and Multi-dimensional arrays in java. b Sorting an array of numbers

Improved Version Complexity Improved Version Complexity Analysis:Analysis: In the improved version for a given input array of size n we now In the improved version for a given input array of size n we now

have:have:T(n)= (n-1) + (n-2) + (n-3) + … + (n-(n-1))= n*(n-1)/2T(n)= (n-1) + (n-2) + (n-3) + … + (n-(n-1))= n*(n-1)/2

This is an improvement over n(n-1) ! BUT:This is an improvement over n(n-1) ! BUT:T(n)= n*(n-1)/2 = O(nT(n)= n*(n-1)/2 = O(n22))

So in terms of complexity the algorithm performs the same order of So in terms of complexity the algorithm performs the same order of operations!operations!

BubbleSort – performs a constant number of operations – for all inputs: BubbleSort – performs a constant number of operations – for all inputs: best case (array is ordered), average case and worst case.best case (array is ordered), average case and worst case.

QuestionsQuestions::- what is the “worst” case?- what is the “worst” case?- can you think of an improvement for “best” and “worst” case?- can you think of an improvement for “best” and “worst” case?