110 likes | 288 Views
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 an integer is an even number or not Algorithm Input a re = a %2 if(re == 0) then a is an even number else a is an odd number.
E N D
Algorithm • Algorithm is a set of steps that are performed to solve a problem. The example below describes an algorithm • Example • Check an integer is an even number or not • Algorithm • Input a • re = a %2 • if(re == 0) then a is an even number • else a is an odd number
Finding maximum, minimum • a is an array of integers. Finding maximum, minimum of array a • max = a[0], min = a[0] • Compare max, min with remain a[i], 1<=i<a.length • If max < a[i] then max = a[i] • If min > a[i] then min = a[i]
Example • a[] = {12, -3, 15, 6, 7} • z[0] = 12, a[1] = -3, a[2] = 5, a[3] = 6, a[4] = 7 • max = a[0] = 12 • i = 1 max = 12 • i = 2 max < a[2] max = 15 • i = 3 max = 15 • i = 4 max = 15
Source code class Maximum{ public static void main(String args[]){ int a[] = {12, -3, 15, 6, 7}; int max = a[0]; for(int i = 1 ; i < a.length ; i++) if(max < a[i]) max = a[i]; System.out.println(max); } }
Sorting array • a is an array of integers. Sorting array a in ascending order • i = 0: finding minimum then place it at a[0] • i = 1: finding minimum from remain elements of array a then place it at a[1] • i = a.length - 2: finding minimum from remain elements of array a then place it at a[a.length - 2]
Example • a[] = {12, -3, 15, 6, 7} • i=0 , min = -3 • i=1, min = 6 • i=2, min = 7 • i=3, min = 12 a[] = {-3, 6, 7, 12, 15}
Source code class Sorting{ public static void main(String args[]){ int a[] = {12, -3, 15, 6, 7}; for(int i = 0 ; i < a.length - 1 ; i++) for(int j = i+1 ; j < a.length ; j++) if(a[i] > a[j]){ int tam = a[i]; a[i] = a[j]; a[j] = tam; } for(int i = 0 ; i < a.length ; i++) System.out.print (a[i] + “\t”); } }
Symmetric aray • a is an array of integers. Check it is a symmetric array or not • a[] = {12, -3, 15, 6, 7} • i=0, a[0] == a[4]. If not exist, else continue • i=1, a[1] == a[3]. If not exist, else continue a[i] = a[a.length – i +1], 0<=i<a.length/2
Source code class Symmetric{ public static void main(String args[]){ int a[] = {12, -3, 15, 6, 7}; for(int i = 0 ; i < a.length/2 ; i++) if(a[i] != a[a.length-i+1]){ System.out.println(“Asymmetric array”); return; } System.out.print (“symmetric array”); } }
Finding the first appearance • a is an array of integers. b is an integer. Finding the first appearance of b in a • a[] = {12, -3, 5, 6, 5} class FirstAppearance{ public static void main(String args[]){ int a[] = {12, -3, 5, 6, 5}; int b = 5; for(int i=0 ; i<a.length ; i++) if(b == a[i]){ System.out.println(“First appearance is” + i); return; } System.out.println(b + “ not appearance in a”); } }