Jan. 20041 Art of Programming Yangjun Chen Dept. Business Computing University of Winnipeg.

Slides:



Advertisements
Similar presentations
CS 1031 Recursion (With applications to Searching and Sorting) Definition of a Recursion Simple Examples of Recursion Conditions for Recursion to Work.
Advertisements

Garfield AP Computer Science
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
Session 3 Algorithm. Algorithm Algorithm is a set of steps that are performed to solve a problem. The example below describes an algorithm Example Check.
Sorting Summary of Sorting Algorithms. _Plan General idea of sorting: we start with an array of items in no particular order, and we want to convert it.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
Recursion.
Quick Sorting -Ed. 2. and 3.: Chapter 10 -Ed. 4.: Chapter 11.
CMPS1371 Introduction to Computing for Engineers SORTING.
Recursion. Idea: Some problems can be broken down into smaller versions of the same problem Example: n! 1*2*3*…*(n-1)*n n*factorial of (n-1)
CSE 373: Data Structures and Algorithms
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
1 TCSS 342, Winter 2005 Lecture Notes Sorting Weiss Ch. 8, pp
Lecture 12 Oct 13, 2008 Some simple recursive programs recursive problem solving, connection to induction Some examples involving recursion Announcements.
Lecture 4 Sept 4 Goals: chapter 1 (completion) 1-d array examples Selection sorting Insertion sorting Max subsequence sum Algorithm analysis (Chapter 2)
交通大學資訊工程學系 Programming in Java More examples, … 蔡文能 交通大學資訊工程學系
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
Chapter 7 (Part 2) Sorting Algorithms Merge Sort.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
Computer Science Searching & Sorting.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
1 Chapter 4: Arrays and strings Taufik Djatna
© 2005 Lawrenceville Press Slide 1 Chapter 5 Relational Operators Relational OperatorMeaning =greater than.
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.
Chapter 9 Searching and Sorting
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Answers to Assignment #1 (Assignment due: Wed. Feb. 05, 2003) 1. What does the "plateform independence" mean? How is it implemented in Java? 2. Summarize.
Java: Review Sept. 2003Yangjun Chen Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.
Multidimensional Arrays. 2 Two Dimensional Arrays Two dimensional arrays. n Table of grades for each student on various exams. n Table of data for each.
CSC 211 Data Structures Lecture 13
1 Today’s Material Iterative Sorting Algorithms –Sorting - Definitions –Bubble Sort –Selection Sort –Insertion Sort.
Comparison-Based Sorting & Analysis Smt Genap
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Some comments on lab4. Hi Philippe! Can you tell me if my code works? Thanks! I’ll show you what works…
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
Array - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/19/20151.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
LECTURE 20: RECURSION CSC 212 – Data Structures. Humorous Asides.
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.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
M180: Data Structures & Algorithms in Java Sorting Algorithms Arab Open University 1.
Computing and the Web Algorithmic Thinking. Overview n Understanding a specific process n Developing an algorithm n Applying the algorithm to computer.
Application development with Java Lecture 6 Rina Zviel-Girshin.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Young CS 331 D&A of Algo. Topic: Divide and Conquer1 Divide-and-Conquer General idea: Divide a problem into subprograms of the same kind; solve subprograms.
COP 3540 Data Structures with OOP
CSE 143 Lecture 16 Sorting reading: 13.1, slides created by Marty Stepp
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Data Structures Arrays and Lists Part 2 More List Operations.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
Building Java Programs Chapter 13 Sorting reading: 13.3, 13.4.
Arrays. What is an array? An array is a collection of data types. For example, what if I wanted to 10 different integers? int num1; int num2; int num3;
Midterm 2 Review Notes on the CS 5 midterm Take-home exam due by 5:00 pm Sunday evening (11/14) Hand in your solutions under the door of my office, Olin.
Sorting and Runtime Complexity CS255. Sorting Different ways to sort: –Bubble –Exchange –Insertion –Merge –Quick –more…
Prof. U V THETE Dept. of Computer Science YMA
Sorting Mr. Jacobs.
Repetition Control Structure in C++ Program
SELECTION STATEMENTS (1)
Searching and Sorting Linear Search Binary Search ; Reading p
מבוא למדעי המחשב, סמסטר א', תשע"א תרגול מס' 2
בתרגול הקודם אתר הקורס (הודעות, פרטי סגל הקורס, עבודות, פורום, מערכת הגשת תרגילים וכו') שימוש בחלון ה-command, פקודות בסיסות קוד Java: הידור (= קומפילציה)
(Assignment due: Wed. Feb. 04, 2004)
CSE 373 Data Structures and Algorithms
CSE 373 Sorting 1: Bogo Sort, Stooge Sort, Bubble Sort
Presentation transcript:

Jan Art of Programming Yangjun Chen Dept. Business Computing University of Winnipeg

Jan Outline: Art of programming Computing factorial Sorting numbers Computing primes

Jan Computing Factorial The factorial of an integer is the product of that number and all of the positive integers smaller than it. -5! = 5*4*3*2*1 = ! =

Jan Computing Factorials A simple class to compute factorials: public class Factorial { public static int factorial(int x) { int fact = 1; for (int i =2; i <= x; i ++)//loop fact *= i;//shorthand for: fact=fact*i; return fact; } public class ComputingFactorial { public static void main(String arg[]) { int a = Factorial.factorial(Integer.parseInt(arg[0])); System.out.println(a); }}

Jan Computing Factorials Recursive Factorials /** * This class shows a recursive method to compute factorials. This method * calls itself repeatedly based on the formula: n! = n*(n-1)! **/ public class Factorial2 { public long factorial(long x) { if (x == 1) return 1; else return x*factorial(x - 1); }

Jan Computing Factorials Caching factorials public class Factorial3 { //create an array to cache values 0! Through 20! Static long[] table = new long[21]; Static {table[0] = 1;} //factorial of 0 is 1 //Remember the highest initialized value in the array static int last = 0; public static long factorial(int x) { while (last < x) { table [last + 1] = table[last]*(last + 1); last++; }}

Jan Sorting Numbers Sorting: Input n numbers, sort them such that the numbers are ordered increasingly

Jan Sorting Numbers A simple sorting algorithm main idea: Algorithm Input: an array A containing n integers. Output: sorted array. 1.i := 2; 2.Find the least element a from A(i) to A(n); 3.If a is less than A(i - 1), exchange A(i - 1) and a; 4. i := i + 1; goto step (2).

Jan Sorting Numbers A simple sorting algorithm main idea: 1st step: nd step: …... swap

Jan Sorting Numbers Sorting program: import java.lang.*; public class SortNumber { public static void sort(double[] nums) { for(int i = 0; i < nums.length - 1; i++) { int min = i +1; for (int j = i+2; j < nums.length; j++) { if (nums[j] < nums[min]) min = j; } if (nums[i] > nums[min]) { double tmp; tmp = nums[i]; nums[i] = nums[min]; nums[min] = tmp;} }}

Jan Sorting Numbers public static void main (String[] args) { double[] nums = new double[10]; //Create an array to hold numbers for(int i = 0; i < nums.length; i++) //Generate random numbers nums[i] = Math.random()*100; sort(nums);//Sort them for (int j = 0; j < nums.length; j++) //Print them out System.out.println(nums [j] ); }

Jan Sorting Numbers Quick sort main idea: Algorithm quick_sort(from, center, to) Input: from - pointer to the starting position of array A center - pointer to the middle position of array A to - pointer to the end position of array A Output: sorted array: A’ 1.Find the first element a = A(i) larger than or equal to A(center) from A(from) to A(to); 2.Find the first element b = A(j) smaller than or equal to A(center) from A(to) to A(from); 3.If i < j then exchange a and b; 4.Repeat step from 1 to 3 until j <= i; 5.If from < j then recursive call quick_sort(from,(from + j)/2, j); 6.If i < to then recursive call quick_sort(i, (i+ to)/2, to);

Jan Sorting Numbers main idea: 1st step: nd step: rd step: centerto Smaller than 5 greater than 5 i j The center element is 5. i = j = 5 Quick sort from

Jan Sorting Numbers 4th step: th step: center from to 3 7 from center i = 2 j =

Jan th step: 1 The sequence contains only one element, no sorting. 7th step: 3 4 i = j = 1 8th step: 4 fromto center The center element is 4. The sequence contains only one element, no sorting

Jan

Jan , 19, 18, -quick sorting 3, 4, 6, 1, 10, 9, 5, 20, 19, 18, 17, 2, 1, 14, 13, 12, 11, 8, 16, 15 3, 4, 6, 1, 10, 9, 5,15, 19, 17, 2, 1, 14, 13, 12, 11, 8, 16,20 18,16,3, 4, 6, 1, 10, 9, 5, 15,17, 2, 1, 14, 13, 12, 11, 8, 20 3, 4, 6, 1, 10, 9, 5, 15, 16, 8,17, 2, 1, 14, 13, 12, 11,19, 20 i=17 j=16 3, 4, 6, 1, 10, 9, 5, 15, 16, 8,17, 2, 1, 14, 13, 12, 11 Sorting Numbers i j

Jan Sorting Numbers Another Java program for the quick sort: public class Sorter { public static void sort (int[] a, int from, int to) { if ((a == null) || (a.length < 2)) return; int i = from, j = to; int center = a[(from + to)/2]; do { while ((i < to) && (a[i] < center)) i++; while ((j > from) && (a[j] > center)) j--; if (i < j) { int tmp =a[i]; a [i] = a[j]; a[j] = tmp;} i++; j--; }while (i <= j);

Jan Sorting Numbers Another Java program for the quick sort: if (from < j) sort(a, from, j); if (i < to) sort(a, i, to); } }

Jan Sorting by merging Merging means the combination of two or more ordered sequence into a single sequence. For example, can merge two sequences: 503, 703, 765 and 087, 512, 677 to obtain a sequence: 087, 503, 512, 677, 703, 765. A simple way to accomplish this is to compare the two smallest items, output the smallest, and then repeat the same process

Jan Merging algorithm Algorithm Merge(s1, s2) Input: two sequences: s1 - x1  x2...  x m and s2 - y1  y2...  y n Output: a sorted sequence: z1  z2...  z m+n. 1.[initialize]i := 1, j := 1, k := 1; 2.[find smaller]if x i  y j goto step 3, otherwise goto step 5; 3.[output x i ] z k.:= x i, k := k+1, i := i+1. If i  m, goto step 2; 4.[transmit y j ...  y n ] z k,..., z m+n := y j,..., y n. Terminate the algorithm; 5.[output y j ] z k.:= y j, k := k+1, j := j+1. If j  n, goto step 2; 6.[transmit x i ...  x m ] z k,..., z m+n := x i,..., x m. Terminate the algorithm;

Jan Merge-sorting Algorithm Merge-sorting(s) Input: a sequences s = Output: a sorted sequence. 1. If |s| = 1, then return s; 2. k :=  m/2  ; 3. s1 := Merge-sorting(x 1,..., x k ); 4. s2 := Merge-sorting(x k+1,..., x m ); 5. return(Merge(s1, s2));

Jan Computing Primes Finding the largest prime number smaller than a specified integer: Input integer m, find p  m such that p is a prime and if there is prime p’ > p then p’ must be larger m. than m

Jan Computing Primes Algorithm main idea: find primes by eliminating multiples of the form k  j, where j is a prime smaller than square-root(m) and k is an integer such that k  j  m prime 2ij   square-root(m) 2222 3333 4444 22 3333 4444 2222 3333 4444 i i i j j j

Jan Computing Primes Import java.lang.*; public class Sieve { public static void main(String[] args) { int max = 100; //Assign a default value try {max = Integer.parseInt(args[0]);} catch (Exception e) {} //Silently ignore exceptions. //Create an array that specifies whether each number is prime or not. boolean[] isprime = new boolean[max+1]; //Assume that all numbers are primes, until proven otherwise. for (int i = 0; i < max; i++) isprime[i] = true; //We know that that 0 and 1 are not prime. Make a note of it. isprime[0] = isprime[1] = false;

Jan Computing Primes //To compute all primes less than max, we need to rule out multiples of all //integers less than the square root of max. int n = (int) Math.ceil(Math.sqrt(max)); for (int i = 0; i <= n; i++) { if (isprime[i]) { int k = 2; for (int j = k*i; j < max; j = (k ++)*i) isprime[j] = false; } } int largest; for (largest = max - 1; !isprime[largest]; largest--); //empty loop body System.out.println(“The largest prime less than or equal to “ + max + “is ” + largest); }}

Jan Assignment #1 (Assignment due: Thu. Feb. 8, 2001) 1. What does the "plateform independence" mean? How is it implemented in Java? 2. Summarize the basic concepts used in Java, such as class, method, variable, Constructor,... (as many as possible) 3. Implement "Caching factorial" and compute 20! using your program. Trace 10 steps of the computation. 4. Implement "quick sort" and sort a sequence containing 20 integers: 3, 4, 6, 1, 10, 9, 5, 20, 19, 18, 17, 2, 1, 14, 13, 12, 11, 8, 16, 15. Trace 10 steps of the computation. 5. Implement "Sieve" and find all the primes smaller than 200 using your program. Trace 10 steps of the computation.