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.

Slides:



Advertisements
Similar presentations
Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Advertisements

Arrays.
Sorting I Chapter 8 Kruse and Ryba. Introduction Common problem: sort a list of values, starting from lowest to highest. –List of exam scores –Words of.
CMPT 225 Sorting Algorithms Algorithm Analysis: Big O Notation.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Analysis of Algorithms CS 477/677 Instructor: Monica Nicolescu Lecture 5.
the fourth iteration of this loop is shown here
For use of IST410 Students only Arrays-1 Arrays. For use of IST410 Students only Arrays-2 Objectives l Declaring arrays l Instantiating arrays l Using.
Simple Sorting Algorithms
Bubble Sort Notes David Beard CS181. Bubble Sort for Strings Double pass algorithm to sort a single dimensional array. Inner loop “bubbles” largest element.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Cmpt-225 Sorting. Fundamental problem in computing science  putting a collection of items in order Often used as part of another algorithm  e.g. sort.
Lecture 4 Sept 4 Goals: chapter 1 (completion) 1-d array examples Selection sorting Insertion sorting Max subsequence sum Algorithm analysis (Chapter 2)
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 08 / 2010 Instructor: Michael Eckmann.
Algorithm Efficiency and Sorting
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Analysis of Algorithm.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Simple Sorting Algorithms. 2 Outline We are going to look at three simple sorting techniques: Bubble Sort, Selection Sort, and Insertion Sort We are going.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Algorithm Analysis & Complexity We saw that a linear search used n comparisons in the worst case (for an array of size n) and binary search had logn comparisons.
1 Week 9 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 17: Arrays Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
26 Sep 2014Lecture 3 1. Last lecture: Experimental observation & prediction Cost models: Counting the number of executions of Every single kind of command.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
Examples using Arrays. Summing Squares Problem: To compute the sum of the squares of N numbers N is given N values are also given These should be read.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
CSE 373 Data Structures and Algorithms
Lecture 6 Sorting Algorithms: Bubble, Selection, and Insertion.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
1 Today’s Material Iterative Sorting Algorithms –Sorting - Definitions –Bubble Sort –Selection Sort –Insertion Sort.
BUBBLE SORT. Introduction Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to.
Data Structure Introduction.
Fundamentals of Algorithms MCS - 2 Lecture # 15. Bubble Sort.
CS 162 Intro to Programming II Bubble Sort 1. Compare adjacent elements. If the first is greater than the second, swap them. Do this for each pair of.
Quicksort CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.
Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Recursion Method calls itself iteratively until a base case is met and usually containing the following: if-else for base case with return value increment/decrement.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
1 Ch. 2: Getting Started. 2 About this lecture Study a few simple algorithms for sorting – Insertion Sort – Selection Sort (Exercise) – Merge Sort Show.
IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD
CS 162 Intro to Programming II Insertion Sort 1. Assume the initial sequence a[0] a[1] … a[k] is already sorted k = 0 when the algorithm starts Insert.
An Object-Oriented Approach to Programming Logic and Design Chapter 8 Advanced Array Concepts.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Shell Sort. Invented by Donald Shell in 1959, the shell sort is the most efficient of the O(n²) class of sorting algorithms. Of course, the shell sort.
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
Dr. Sajib Datta CSE 1320 Arrays, Search and Sort.
ARRAYS Multidimensional realities Image courtesy of
SORTING Sorting is storage of data in some order, it can be in ascending or descending order. The term Sorting comes along-with the term Searching. There.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
UNIT - IV SORTING By B.Venkateswarlu Dept of CSE.
Arrays.
Linear and Binary Search
Describing algorithms in pseudo code
Algorithms Analysis Algorithm efficiency can be measured in terms of:
Sorting.
Presentation transcript:

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 using the BubbleSort algorithm, pseudo-code and java implementation. b Complexity analysis (running time) of the BubbleSort algorithm.

Constructors revisited: b There are 3 basic types of constructors that can be defined for a class: 1)Default constructor – a constructor that receives no parameters. If no constructors are defined – the compiler automatically creates an empty default constructor. 2)Insertion constructor – any constructor that receives some parameters which are used to initialize the data members of the object created. 3)Copy constructor – a constructor which receives a ref to an object of the same class – and uses it to copy the ‘internal state’ (all data members) of that object to the newly created object. This constructor creates a new copy of the object it receives as a parameter.

Constructor example: public class NumberedRectangle { private int serialNumber; private Point p1; //lower left corner. private Point p2 // upper right corner. //default constructor public NumberedRectangle(){ serialNumber= 0; p1= new Point(0,0); p2= new Point(1,1); } //insertion constructor public NumberedRectangle(int serialNumber, Point p1, Point p2){ this.serialNumber= serialNumber; this.p1= new Point(p1); this.p2= new Point(p2); }

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 b b 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!

Constructor overloading b In java a class can have more than one constructor defintion. This is called Constructor Overloading and is a special case of Method overloading (will be addressed in future lessons) b The compiler knows which constructor to call by looking at the parameters that are passed to the constructor, when it is called. Therefore – the constructors must differ in their parameter lists: they can have a different number of parameters, or different kinds of parameters.

Two-Dimensional Arrays: declaration and initialization b A two dimensional array – is actually an array of arrays. b Declaration: boolean[ ][ ] table; Table is a reference to a 2-dimensional array of booleans which is uninitialized. b Initialization: option I: table= new boolean[10][5]; 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.

Two-Dimensional Arrays: declaration and initialization b Option II: table= new boolean[3][ ]; table[0] = new boolean[3]; table[1]= new boolean[10]; table[2]= new boolean[2]; b 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 initialized separately – if they are not all initialized using option I.

2-dim arrays with different lengths: b Example: int intArray2D[ ][ ] = new int[5][ ]; for(int i=0; i<intArray2D.length; i++) intArray2D[i] = new int[i+1]; b What we have now is: intArray2D[0] intArray2D[1] intArray2D[2] intArray2D[3] intArray2D[4]

Accessing a 2-dim array: b Accesing the arrays is done using indices: table[0][1]= true; Or: if( table[i][j] ) //some code

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 Example

Multidimensional Arrays b In java we can define arrays of any dimension. This can be thought of as an array of arrays of arrays… b Each array can have a different size which will be denoted by its length field. b Example: int[][][] counts= new int[2][2][ ]; counts[0][1]= new int[10]; counts[1][1]= new int[20]; … counts[0][0][0]= 100;

Multi 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}};

Arrays 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")}};

Permutation 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:

Permutation 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(); }

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...

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; }

Sorting an array of numbers- Buble Sort b Sorting is a basic task used in many different contexts. b There are many different algorithms to sort a list of numbers, (or any other objects which can be ordered). b We present a simple naïve sorting algorithm called BubbleSort. b Basic idea: each time “bubble” largest element left in the array to its place at the end of the array, until all values are positioned in their “correct” place.

BubbleSort – PseudoCode: Notice different notation: this is just intended to be readable for any programmer in ANY language! Notice different notation: this is just intended to be readable for any programmer in ANY language! //assume A is an array of numbers of size n. BubbleSort(A){ (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 ( ) swap(A,j,j+1); ( ) swap(A,j,j+1);} //swap two values in the array A in indices i, and j. swap(A,i,j){ (1) temp  A[i]; (2) A[i]  A[j]; (3) A[j]  temp; }

BubbleSort: java code: public void bubbleSort(int[] array){ 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+1]= temp; }}

BubbleSort – complexity analysis b We want to measure how efficient is the algorithm. b You have seen in class that the standard way of doing this is by analyzing the number of operations that the algorithm performs for a given input of size n. b we measure the running time of the algorithms as a function of the input size n. b In our case – the input size is : the Array’s size! b BubbleSort running time: for an array of size n how many times will we evaluate the if statement (and decide if to swap or not to swap 2 values)?

BubbleSort – complexity analysis b Anlysis: outer loop: n times, each time runs inner loop n-1 iterations: total is: n(n-1) if evaluations. b We write: T(n)= n(n-1)= O(n 2 ) using the “Big O” notation shown in class. b Question: can we improve the BubbleSort algorithm shown here?

BubbleSort – improved version: b 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 array – and we don’t need to compare any of the other numbers to it again – it will never be moved from that location! public void bubbleSort(int[] array){ for(int i=0; i<array.length; i++) for(int j=0; j<array.length-(i+1); j++) for(int j=0; j<array.length-(i+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+1]= temp; }}

Improved Version Complexity Analysis: b In the improved version for a given input array of size n we now have: T(n)= (n-1) + (n-2) + (n-3) + … + (n-(n-1))= n*(n-1)/2 b This is an improvement over n(n-1) ! BUT: T(n)= n*(n-1)/2 = O(n 2 ) So in terms of complexity the algorithm performs the same order of operations! BubbleSort – performs a constant number of operations – for all inputs: best case (array is ordered), average case and worst case. Questions: - what is the “worst” case? - can you think of an improvement for “best” and “worst” case?