Está en la página 1de 88

Advanced Problem Solving

Advanced Problem Solving

12JJ1D4001

12JJ1D4001_1A.java Program 1: 1.A) Write a Java program that prints all real solutions to the quadratic equation ax2 + bx + c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b2 4ac is negative; display a message stating that there are no real solutions.

import java.lang.Math; import java.util.InputMismatchException; import java.util.Scanner; class Program1A_4001 { double a, b, c; Program1A_4001(double a, double b, double c) { this.a = a; this.b = b; this.c = c;
JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

Advanced Problem Solving } public void getRoots() { if (a == 0.0) {

12JJ1D4001

System.out.println("This Equation Has Only One root = " + (-c / b)); return; } double d = b * b - 4.0 * a * c; if (d < 0) { System.out.println("Roots are imaginary..."); return; } if (d == 0) { System.out.println("The Two roots are equal: " + (-b / (2.0 * a))); return; } double x1 = (-b + Math.sqrt(d)) / (2.0 * a); double x2 = (-b - Math.sqrt(d)) / (2.0 * a); System.out.println("The Two Roots are: " + x1 + ", " + x2); } public static void main(String[] args) { try { Scanner sc = new Scanner(System.in); System.out.println("Enter a,b,c values..."); double a = sc.nextDouble(); double b = sc.nextDouble();

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

Advanced Problem Solving double c = sc.nextDouble(); Program1A_4001 qer = new Program1A_4001(a, b, c); qer.getRoots(); sc.close(); } catch (InputMismatchException e) { System.out.println("You Have Entered Wrong Input..."); } } }

12JJ1D4001

Output : .\12JJ1D4001 > javac Program1A_4001.java .\12JJ1D4001 > java Program1A_4001 Enter a,b,c values... 1 5 6 The Two Roots are: -2.0, -3.0 .\12JJ1D4001 > java Program1A_4001 Enter a,b,c values... 1 2 1 The Two roots are equal: -1.0 .\12JJ1D4001 > java Program1A_4001 Enter a,b,c values... 1 2

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

Advanced Problem Solving 3 Roots are imaginary...

12JJ1D4001

12JJ1D4001_1B.java 1.B) The Fibonacci sequence is defined by the following rule: The first two values in the sequence are 0 and 1. Every subsequent value is the sum of the two values preceding it. Write a Java program that uses both recursive and non-recursive functions to print the nth value in the Fibonacci sequence.

import java.util.Scanner; public class Program1B_4001 { public int fibonacciSeq(int n) { int term1 = 0, term2 = 1, nextTerm = 0; if (n == 0 || n == 1) return n; int count = 2; while (count <= n) { nextTerm = term1 + term2; term1 = term2; term2 = nextTerm; count++; } return nextTerm; }
JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

Advanced Problem Solving

12JJ1D4001

public int recFibonacciSeq(int n) { if (n == 0 || n == 1) return n; else return (recFibonacciSeq(n - 1) + recFibonacciSeq(n - 2)); } public static void main(String[] args) { int n = 0; Program1B_4001 fb = new Program1B_4001(); Scanner sc = new Scanner(System.in); System.out.println("Enter 'n' Value"); n = sc.nextInt(); System.out.println("Febonacci Number " + n + " Using Iterative Method is : " + fb.fibonacciSeq(n)); System.out.println("Febonacci Number " + n + " Using Recursive Method is : " + fb.recFibonacciSeq(n)); sc.close(); } } Output : .\12JJ1D4001 > javac Program1B_4001.java .\12JJ1D4001 > java Program1B_4001 Enter 'n' Value 25 Febonacci Number 25 Using Iterative Method is : 75025 Febonacci Number 25 Using Recursive Method is : 75025

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

Advanced Problem Solving

12JJ1D4001

12JJ1D4001_2A.java Program 2 : 2.A) Write a Java program that prompts the user for an integer and then prints out all prime numbers up to that integer import java.io.IOException; import java.util.Scanner; public class Program2A_4001 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); System.out.println("Enter 'n' Value"); int n = sc.nextInt(); for (int m = 1; m <= n; m++) { int count = 0; for (int i = 1; i <= m; i++) { if (m % i == 0) { count++; } } if (count == 2) { System.out.println( m+"\t");
JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

Advanced Problem Solving } } sc.close(); } } Output : .\12JJ1D4001 > javac Program2A_4001.java .\12JJ1D4001 > java Program2A_4001 Enter 'n' Value 17 2 3 5 7 11 13

12JJ1D4001

17

12JJ1D4001_2B.java 2.B) Write a java program to multiply two given matrices. import java.io.*; import java.lang.*; import java.util.*; public class Program2B_4001 { public static void main(String args[]) { int sum = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter The Size(rows & columns) of First Matrix"); int p = sc.nextInt(); int q = sc.nextInt(); int a[][] = new int[p][q]; System.out.println("Enter The Elements of First Matrix"); for (int i = 0; i < p; i++) { for (int j = 0; j < q; j++) { a[i][j] = sc.nextInt(); } } System.out.println("Enter The Size(rows & columns) of Second Matrix"); int m = sc.nextInt();

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

Advanced Problem Solving

12JJ1D4001

int n = sc.nextInt(); int b[][] = new int[m][n]; if (q != m) { System.out.println("Multiplication cannot be performed"); } else { System.out.println("Enter The Elements of Second Matrix"); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) b[i][j] = sc.nextInt(); } int c[][] = new int[p][n]; for (int i = 0; i < p; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { sum = sum + a[i][k] * b[k][j]; } c[i][j] = sum; sum = 0; } } System.out.println("Multiplication result matrix elemnets are"); for (int i = 0; i < p; i++) { for (int j = 0; j < n; j++) { System.out.println(c[i][j]); } } } } } Output : .\12JJ1D4001 > javac Program2B_4001.java .\12JJ1D4001 > java Program2B_4001 Enter The Size(rows & columns) of First Matrix 32 Enter The Elements of First Matrix 123456 Enter The Size(rows & columns) of Second Matrix 23

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

Advanced Problem Solving Enter The Elements of Second Matrix 987564 Multiplication result matrix elemnets are 19 20 15 47 48 37

12JJ1D4001

75

76

59

12JJ1D4001_2C.java 2.C) Write a Java Program that reads a line of integers, and then displays each integer, and the sum of all the integers (use StringTokenizer class of java.util). import java.util.Scanner; import java.util.StringTokenizer; public class Program2C_4001 { public static void main(String[] args) { String str = null; int n = 0, sum = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter String of Integers Separated With Spaces"); str = sc.nextLine(); StringTokenizer st = new StringTokenizer(str); System.out.println("The given integers are : "); while (st.hasMoreElements()) { n = Integer.parseInt(st.nextElement().toString()); System.out.println(n); sum = sum + n; } System.out.println("The sum of given integers is : " + sum); sc.close();

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

Advanced Problem Solving } }

12JJ1D4001

Output : .\12JJ1D4001 > javac Program2C_4001.java .\12JJ1D4001 > java Program2C_4001 Enter String of Integers Separated With Spaces 123456 The given integers are : 1 2 3 4 5 6 The sum of given integers is : 21 12JJ1D4001_3.java Program 3: Write a java program to find both the largest and smallest numbers in a list of integers. class Program3_4001 { public void sort(int[] a) { int i, pass, n = a.length; int tmp; for (pass = 0; pass < n; pass++) { for (i = 0; i < n - pass - 1; i++) if (a[i] > a[i + 1]) { tmp = a[i]; a[i] = a[i + 1]; a[i + 1] = tmp; } } } public static void main(String[] args) { Program3_4001 sn = new Program3_4001 (); int[] nums = { 777, 555, 222, 666, 888, 333, 444 }; int i;

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

10

Advanced Problem Solving System.out.println("Unsorted Numbers :"); for (i = 0; i < nums.length; i++) System.out.print(nums[i]+ "\t"); System.out.println(); sn.sort(nums); System.out.println("Sorted Numbers :"); for (i = 0; i < nums.length; i++) System.out.print(nums[i]+ "\t"); System.out.println(); System.out.println("Smallest Number is : " + nums[0]); System.out.println("largest Number is : " + nums[nums.length - 1]); } } Output : .\12JJ1D4001 > javac Program3_4001.java .\12JJ1D4001 > java Program3_4001 Unsorted Numbers : 777 555 222 666 888 333 Sorted Numbers : 222 333 444 555 666 777 Smallest Number is : 222 largest Number is : 888

12JJ1D4001

444 888

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

11

Advanced Problem Solving

12JJ1D4001

12JJ1D4001_4.java Program 4: Write a java program to illustrate method overloading. public class Program4_4001 { public void add(int a, int b) { System.out.println("Two Integers Sum is : " + (a + b)); } public void add(String str1, String str2) { System.out.println("Two Strings Sum is : " + (str1 + str2)); } public static void main(String[] args) { Program4_4001 mo = new Program4_4001 (); mo.add(5, 6); mo.add("hai", "hello"); } } Output : .\12JJ1D4001 > javac Program4_4001.java

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

12

Advanced Problem Solving .\12JJ1D4001 > java Program4_4001 Two Integers Sum is : 11 Two Strings Sum is : haihello

12JJ1D4001

12JJ1D4001_5.java Program 5 : Write a java program to sort a list of names in ascending order. class Program5_4001 { public void sort(String[] a) { int i, pass, n = a.length; String tmp; for (pass = 0; pass < n; pass++) { for (i = 0; i < n - pass - 1; i++) if (a[i].compareTo(a[i + 1]) > 0) { tmp = a[i]; a[i] = a[i + 1]; a[i + 1] = tmp; } } } public static void main(String[] args) { Program5_4001 sn = new Program5_4001(); String[] names = { "JWT", "LP", "APS", "HSN", "CSD", "IRS" }; int i; System.out.println("Unsorted names:");

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

13

Advanced Problem Solving for (i = 0; i < names.length; i++) System.out.print(names[i]+ "\t"); System.out.println(); sn.sort(names); System.out.println("Sorted names:"); for (i = 0; i < names.length; i++) System.out.print(names[i]+ "\t"); } } Output : .\12JJ1D4001 > javac Program5_4001.java .\12JJ1D4001 > java Program5_4001 Unsorted names: JWT LP APS HSN CSD IRS Sorted names: APS CSD HSN IRS JWT LP

12JJ1D4001

12JJ1D4001_6.java Program 6 : Write a program to implement matrix ADT that performs the following operations: a)Reading Matrix b)Addition of Matrices c)Subtraction of Matrices d)Display of Matrices e)Multiplication of Matrices import java.util.Scanner; class Program6_4001 { public static void main(String args[]) { int ch; MatDemo ob = new MatDemo(); while (true) { System.out.println("Enter the choice for operation of mat as:"); System.out.println("1.ReadMat\n2.AddMat\n3.SubMat\n4.DispMat\n 5.MulMat\n6.Exit"); Scanner sc = new Scanner(System.in); ch = sc.nextInt(); switch (ch) { case 1: ob.ReadMat(); break;
JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

14

Advanced Problem Solving case 2: ob.AddMat(); break; case 3: ob.SubMat(); break; case 4: ob.DispMat(); break; case 5: ob.MulMat(); break; case 6: System.exit(0); default: System.out.println("Enter a valid choice:"); break; } } } } class MatDemo { int r, c; int A[][] = new int[3][3]; int B[][] = new int[3][3]; int i, j; int C[][] = new int[3][3]; public void ReadMat() { System.out.println("Enter the values of r and c:"); Scanner sc = new Scanner(System.in); r = sc.nextInt(); c = sc.nextInt(); System.out.println("Enter the values of A matrix:"); for (i = 0; i < r; i++) for (j = 0; j < c; j++) A[i][j] = sc.nextInt(); System.out.println("Enter the values of B matrix:"); for (i = 0; i < r; i++) for (j = 0; j < c; j++)

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

15

Advanced Problem Solving B[i][j] = sc.nextInt(); } public void AddMat() { for (i = 0; i < r; i++) for (j = 0; j < c; j++) C[i][j] = A[i][j] + B[i][j]; System.out.println("Res of Addition is:"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { System.out.print(C[i][j] + " "); } System.out.println(); } } public void SubMat() { for (i = 0; i < r; i++) for (j = 0; j < c; j++) C[i][j] = A[i][j] - B[i][j]; System.out.println("Res of Subtraction is:"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { System.out.print(C[i][j] + " "); } System.out.println(); } } public void DispMat() { System.out.println("Value of Mat A:"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { System.out.print(A[i][j] + " "); } System.out.println(); } System.out.println("Value of Mat B:"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { System.out.print(B[i][j] + " "); } System.out.println();

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

16

Advanced Problem Solving } System.out.println("Value of Mat C:"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { System.out.print(C[i][j] + " "); } System.out.println(); } } public void MulMat() { if (r == c) for (i = 0; i < r; i++) for (j = 0; j < c; j++) { C[i][j] = 0; for (int k = 0; k < c; k++) C[i][j] = C[i][j] + A[i][k] * B[k][j]; } System.out.println("Res of Multiplication is:"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { System.out.print(C[i][j] + " "); } System.out.println(); } } } Output : .\12JJ1D4001 > javac Program6_4001.java .\12JJ1D4001 > java Program6_4001 Enter the choice for operation of mat as: 1.ReadMat 2.AddMat 3.SubMat 4.DispMat 1 Enter the values of r and c: 2 2 Enter the values of A matrix: 1 0 0 1 Enter the values of B matrix: 2 2 2 2

12JJ1D4001

5.MulMat

6.Exit

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

17

Advanced Problem Solving Enter the choice for operation of mat as: 1.ReadMat 2.AddMat 3.SubMat 4.DispMat 2 Res of Addition is: 32 23 Enter the choice for operation of mat as: 1.ReadMat 2.AddMat 3.SubMat 4.DispMat 3 Res of Subtraction is: -1 -2 -2 -1 Enter the choice for operation of mat as: 1.ReadMat 2.AddMat 3.SubMat 4.DispMat 5 Res of Multiplication is: 22 22 Enter the choice for operation of mat as: 1.ReadMat 2.AddMat 3.SubMat 4.DispMat 4 Value of Mat A: 10 01 Value of Mat B: 22 22 Value of Mat C: 22 22 Enter the choice for operation of mat as: 1.ReadMat 2.AddMat 3.SubMat 4.DispMat 6

12JJ1D4001

5.MulMat

6.Exit

5.MulMat

6.Exit

5.MulMat

6.Exit

5.MulMat

6.Exit

5.MulMat

6.Exit

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

18

Advanced Problem Solving

12JJ1D4001

12JJ1D4001_7.java Program 7 : Write a java program that uses a recursive function to compute ncr. import java.util.Scanner; class Program7_4001 { double fact(int n) { double result; if (n == 1) return 1; result = fact(n - 1) * n; return result; } public double getNCR(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } public static void main(String[] args) { int n, r; double result;

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

19

Advanced Problem Solving Scanner sc = new Scanner(System.in); Program7_4001 res = new Program7_4001(); System.out.println("Enter n & r values"); n = sc.nextInt(); r = sc.nextInt(); result = res.getNCR(n, r); System.out.println("The Result is : " + result); sc.close(); } } Output : .\12JJ1D4001 > javac Program7_4001.java .\12JJ1D4001 > java Program7_4001 Enter n & r values 15 2 The Result is : 105.0

12JJ1D4001

12JJ1D4001_8.java Program 8 : Write a java program to perform following operations. a) Concatenation of two strings. b) Comparision of two strings. import java.util.Scanner; public class Program8_4001 { public static void main(String[] args) { String str1 = "APS"; String str2 = "JWT"; System.out.println("The Concatenation of two strings ( " + str1 + " & " + str2 + " ) is : " + (str1 + str2)); System.out.println("The Comparison of two strings ( " + str1 + " & " + str2 + " ) is : " + (str1.compareTo(str2))); System.out.println("The Comparison of two strings ( " + str2 + " & " + str1 + " ) is : " + (str2.compareTo(str1))); System.out.println("The Comparison of two strings ( " + str1 + " & " + str1 + " ) is : " + (str1.compareTo(str1))); }

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

20

Advanced Problem Solving }

12JJ1D4001

Output : .\12JJ1D4001 > javac Program8_4001.java .\12JJ1D4001 > java Program8_4001 The Concatenation of two strings ( APS & JWT ) is : APSJWT The Comparison of two strings ( APS & JWT ) is : -9 The Comparison of two strings ( JWT & APS ) is : 9 The Comparison of two strings ( APS & APS ) is : 0

12JJ1D4001_9.java Program 9 : Write a java program that makes frequency count of letters in a given text. import java.io.*; import java.util.*; class Program9_4001 { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter string "); System.out.println(); String str = br.readLine(); String st = str.replaceAll(" ", ""); char[] third = st.toCharArray(); for (int counter = 0; counter < third.length; counter++) { char ch = third[counter]; int count = 0; for (int i = 0; i < third.length; i++) { if (ch == third[i])

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

21

Advanced Problem Solving count++;

12JJ1D4001

} boolean flag = false; for (int j = counter - 1; j >= 0; j--) { if (ch == third[j]) flag = true; } if (!flag) { System.out.println("Character :" + ch + " occurs " + count + " times "); } } } }

Output : .\12JJ1D4001 > javac Program9_4001.java .\12JJ1D4001 > java Program9_4001 Please enter string hello world how r u Character :h occurs 2 times Character :e occurs 1 times Character :l occurs 3 times Character :o occurs 3 times Character :w occurs 2 times Character :r occurs 2 times Character :d occurs 1 times Character :u occurs 1 times

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

22

Advanced Problem Solving

12JJ1D4001

12JJ1D4001_10.java Program 10 : Write a java program that uses functions to perform following operations a)Inserting a sub-string in to the given main string from a given position. b)Deleting n characters from a given position in a given string. import java.util.Scanner; public class Program10A_4001 { static StringBuffer sb = new StringBuffer(); public static void main(String[] args) { sb.append("Hello World"); Program10A_4001 obj=new Program10A_4001(); Scanner sc = new Scanner(System.in); while (true) { System.out.println("Main Menu\n1.Insert String\t2.Delete String\t3.exit"); System.out.println("choose ur choice"); int ch = sc.nextInt(); switch (ch) { case 1: System.out.println("Enter String To Insert"); String str = sc.next();

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

23

Advanced Problem Solving

12JJ1D4001

System.out.println("Enter Position(starts from '0')"); int n1 = sc.nextInt(); obj.insertSubstring(n1, str); break; case 2: System.out.println("How many characters you want to delete?"); int n = sc.nextInt(); System.out.println("Enter Position(starts from '0')"); int m = sc.nextInt(); obj.deleteSubstring(m,n); break; case 3: System.exit(0); } } } public void insertSubstring(int index,String str) { System.out.println("The string before inserting : " + sb.toString()); sb.insert(index, str); System.out.println("The string after inserting : " + sb.toString()); } public void deleteSubstring(int m,int n) { System.out.println("The string before deleting : " + sb.toString()); sb.delete(m, m + n); System.out.println("The string after deleting : " + sb.toString()); } } Output : .\12JJ1D4001 > javac Program10_4001.java .\12JJ1D4001 > java Program10_4001 Main Menu 1.Insert String 2.Delete String 3.exit choose ur choice 1 Enter String To Insert hai Enter Position(starts from '0') 4

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

24

Advanced Problem Solving The string before inserting : Hello World The string after inserting : Hellhaio World Main Menu 1.Insert String 2.Delete String 3.exit choose ur choice 2 How many characters you want to delete? 3 Enter Position(starts from '0') 4 The string before deleting : Hellhaio World The string after deleting : Hello World

12JJ1D4001

12JJ1D4001_11A.java Program 11 : 11. A) Write a java program that checks whether a given string is a palindrome or not. import java.util.Scanner; class Program11A_4001 { public boolean isPalindrome(String str) { int n = str.length(); boolean flag = true; for (int i = 0; i < n / 2; i++) if (str.charAt(i) != str.charAt(n - i - 1)) flag = false; return flag; } public static void main(String[] args) { Program11A_4001 pal = new Program11A_4001(); Scanner sc = new Scanner(System.in); System.out.println("Enter A String"); String str = sc.nextLine().trim(); if (pal.isPalindrome(str)) System.out.print("The Given String Is A Palindrome");

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

25

Advanced Problem Solving else System.out.print("The Given String Is Not A Palindrome"); sc.close(); } } Output : .\12JJ1D4001 > javac Program11A_4001.java .\12JJ1D4001 > java Program11A_4001 Enter A String madam The Given String Is A Palindrome .\12JJ1D4001 > java Program11A_4001 Enter A String hello The Given String Is Not A Palindrome

12JJ1D4001

12JJ1D4001_11B.java 11. B) Write a java program to make frequency count of words in a given text. import java.util.*; import java.io.*; class Program11B_4001 { private static Hashtable WordFrequency = new Hashtable(); public static void main(String args[]) { System.out.println("Enter the source string for frequency count:"); Scanner in = new Scanner(System.in); int count; String word; countWords(in.nextLine()); for (Enumeration str = WordFrequency.keys(); str.hasMoreElements();) { word = (String) str.nextElement(); count = ((Integer) WordFrequency.get(word)).intValue(); System.out.println("word:" + word + " count:" + count); } }

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

26

Advanced Problem Solving

12JJ1D4001

public static void countWords(String source) { String nextword; int count = 0; Scanner wordscanner = new Scanner(source); wordscanner.useDelimiter("[^A-Za-z0-9]+"); while (wordscanner.hasNext()) { nextword = wordscanner.next(); if (WordFrequency.containsKey(nextword)) { count = ((Integer) WordFrequency.get(nextword)).intValue(); count++; WordFrequency.put(nextword, Integer.valueOf(count)); } else WordFrequency.put(nextword, Integer.valueOf(1)); } } } Output : .\12JJ1D4001 > javac Program11B_4001.java .\12JJ1D4001 > java Program11B_4001 Enter the source string for frequency count: hello hai hw hai you word:hw count:1 word:hai count:2 word:hello count:1 word:you count:1

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

27

Advanced Problem Solving

12JJ1D4001

12JJ1D4001_12A.java Program 12 : 12. A) Develop an applet in java that displays a simple message. import java.applet.*; import java.awt.*; public class Program12A_4001 extends Applet { public static long fact(int n) { long fact = 1; for (int i = n; i > 0; i--) { fact = fact * i; } return fact; } public void paint(Graphics g) { g.drawString("Hello World", 100, 100); } }

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

28

Advanced Problem Solving

12JJ1D4001

Output : .\12JJ1D4001 > javac Program12A_4001.java .\12JJ1D4001 > appletviewer Program12A_4001.java

12JJ1D4001_12B.java 12.B) Develop an applet in java that receives an integer in one text field, and computes its factorial value and returns it in another text field, when the button compute is clicked. import java.applet.Applet; import java.awt.Button; import java.awt.Label; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Program12B_4001 extends Applet implements ActionListener { TextField t1, t2; Label l1, l2; Button b1; double fact = 1; int m; String msg; public void init() { t1 = new TextField(3); t2 = new TextField(15); b1 = new Button("COMPUTE");

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

29

Advanced Problem Solving l1 = new Label("ENTER NUMBER"); l2 = new Label("FACTORIAL"); add(l1); add(t1); add(l2); b1.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String str = t1.getText(); if (str != "") { int num = Integer.parseInt(str); for (int i = num; i > 0; i--) { fact = fact * i; } msg = "" + fact; t2.setText(msg); fact = 1; } } } Output : .\12JJ1D4001 > javac Program12B_4001.java .\12JJ1D4001 > appletviewer Program12B_4001.java

12JJ1D4001

add(t2);

add(b1);

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

30

Advanced Problem Solving

12JJ1D4001

12JJ1D4001_12C.java 12. C) Write a java program that allows the user to draw lines, rectangles and ovals. import java.awt.*; import java.applet.*; public class Program13_4001 extends Applet { public void paint(Graphics g) { Color c1 = new Color(35, 55, 110); g.setColor(c1); g.drawRect(130, 80, 50, 50); g.drawOval(60, 50, 40, 40); g.drawLine(50, 20, 10, 10); } } Output : .\12JJ1D4001 > javac Program12C_4001.java .\12JJ1D4001 > appletviewer Program12C_4001.java

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

31

Advanced Problem Solving

12JJ1D4001

12JJ1D4001_13A.java Program 13 : 13. A) Write a java program that illustrates how to create a simple package. package Program13A_4001; import java.util.ArrayList; public class Program13A_4001 { ArrayList<String> marks = new ArrayList<String>(); public void insert(String s, int n) { marks.add(s + " : " + n); } public void show() { for (String mark : marks) { System.out.println(mark); }
JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

32

Advanced Problem Solving } public static void main(String args[]) { Program13A_4001 obj = new Program13A_4001(); obj.insert("subject", 100); obj.show(); } } Output : .\12JJ1D4001 >md Program13A_4001 .\12JJ1D4001 >javac Program13A_4001.java .\12JJ1D4001 >java Program13A_4001. Program13A_4001 subject : 100

12JJ1D4001

12JJ1D4001_13B.java 13. B) Write a java program that illustrates how to access a package. import Program13A_4001.Program13A_4001; public class Program13B_4001 { public static void main(String[] args) { Program13A_4001 obj = new Program13A_4001(); obj.insert("APS", 95); obj.insert("JWT", 90); obj.show(); } }

Output : .\12JJ1D4001 >javac Program13B_4001.java .\12JJ1D4001 >java Program13B_4001 APS : 95 JWT : 90

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

33

Advanced Problem Solving

12JJ1D4001

12JJ1D4001_13C.java 13. C) Write a java program that illustrates how to implement interfaces. interface operations { int add(int a, int b); int subtract(int a, int b); String concat(String s1, String s2); } class Program13C_4001 implements operations { public int add(int a, int b) { return a + b; } public int subtract(int a, int b) { return a - b; } public String concat(String s1, String s2) { return s1 + s2; } public static void main(String args[]) { Program13C_4001 obj = new Program13C_4001();

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

34

Advanced Problem Solving int add = obj.add(10, 20); int sub = obj.subtract(50, 10); String concat = obj.concat("hello", "hai"); System.out.println("Addition result : " + add); System.out.println("Subtraction result : " + sub); System.out.println("Concatenation result : " + concat); } } Output : .\12JJ1D4001 >javac Program13C_4001.java .\12JJ1D4001 >java Program13C_4001 Addition result : 30 Subtraction result : 40 Concatenation result : hellohai

12JJ1D4001

12JJ1D4001_14A.java Program 14 : 14. A) Write a java program to implement stack ADT using arrays. import java.util.Scanner; public class Program14A_4001 { private int top; private int[] storage; Program14A_4001(int capacity) { if (capacity <= 0) System.out.println("Stack size must be greater than zero"); else { storage = new int[capacity]; top = -1; } } void push(int value) { if (top == storage.length - 1) System.out.println("Stack is overflow");
JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

35

Advanced Problem Solving else { storage[++top] = value; }

12JJ1D4001

} void peek() { if (top == -1) System.out.println("Stack is empty"); else System.out.println(storage[top]); } void display() { if (top == -1) System.out.println("Stack is empty"); else { for (int i = 0; i <= top; i++) { System.out.print(storage[i] + "\t"); } System.out.println(); } } void pop() { if (top == -1) System.out.println("Stack is underflow"); else System.out.println(storage[top--] + " deleted"); } public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter size of stack"); Program14A_4001 obj = new Program14A_4001(sc.nextInt()); while (true) { System.out.println("Main Menu\n1.Push\t2.Pop\t3.Display\t4.Peek\t5.exit"); System.out.println("choose ur choice"); int ch = sc.nextInt(); switch (ch) { case 1: System.out.println("Enter elemnet to Push"); int n1 = sc.nextInt(); obj.push(n1); break;

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

36

Advanced Problem Solving case 2: obj.pop(); break; case 3: obj.display(); break; case 4: obj.peek(); break; case 5: System.exit(0); default: System.out.println("Choose Correct Option"); break; } } } } Output : .\12JJ1D4001 > javac Program14A_4001.java .\12JJ1D4001 > java Program14A_4001 Enter size of stack 3 Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit choose ur choice 1 Enter elemnet to Push 10 Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit choose ur choice 1 Enter elemnet to Push 11 Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

37

Advanced Problem Solving choose ur choice 1 Enter elemnet to Push 12 Main Menu 1.Push 2.Pop 3.Display choose ur choice 1 Enter elemnet to Push 13 Stack is overflow Main Menu 1.Push 2.Pop 3.Display choose ur choice 3 10 11 12 Main Menu 1.Push 2.Pop 3.Display choose ur choice 4 12 Main Menu 1.Push 2.Pop 3.Display choose ur choice 2 12 deleted Main Menu 1.Push 2.Pop 3.Display choose ur choice 3 10 11 Main Menu 1.Push 2.Pop 3.Display choose ur choice 2 11 deleted Main Menu 1.Push 2.Pop 3.Display choose ur choice 3

12JJ1D4001

4.Top Element 5.exit

4.Top Element 5.exit

4.Top Element 5.exit

4.Top Element 5.exit

4.Top Element 5.exit

4.Top Element 5.exit

4.Top Element 5.exit

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

38

Advanced Problem Solving 10 Main Menu 1.Push 2.Pop 3.Display choose ur choice 5

12JJ1D4001

4.Top Element 5.exit

12JJ1D4001_14B.java 14. B) Write a java program to implement queue ADT using arrays. import java.util.Scanner; public class Program14B_4001 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter size of queue"); QueueOs2 q = new QueueOs2(sc.nextInt()); int ch; do { System.out.println("1.push\t2.pop\t3.display\t4.destroy\t5.exit"); System.out.println("Enter your choice :"); ch = sc.nextInt(); switch (ch) { case 1: System.out.println("Enter data to insert"); int x = sc.nextInt(); q.push(x); break;

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

39

Advanced Problem Solving case 2: if (q.isEmpty()) System.out.println("Queue underflow"); else { int z = q.pop(); System.out.println("data deleted =" + z); } break; case 3: q.display(); break; case 4: q.destroy(); break; case 5: System.exit(0); default: System.out.println("Wrong Choice"); } } while (ch != 5); } } class QueueOs2 { int a[]; int front, rear; QueueOs2(int size) { a = new int[size]; front = rear = -1; } void push(int x) { int p; p = (rear + 1) % a.length; if (p == front) System.out.println("Queue Overflow "); else { rear = p; a[rear] = x; if (front == -1) front = 0; }

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

40

Advanced Problem Solving } boolean isEmpty() { if (front == -1) return true; else return false; } int pop() { int x = a[front]; if (front == rear) front = rear = -1; else front = (front + 1) % a.length; return x; } void display() { if (front == -1) System.out.println("Queue underflow"); else { System.out.println("Elements of Queue are"); int i = front; while (i != rear) { System.out.print(a[i] + "\t"); i = (i + 1) % a.length; } System.out.println(a[i]); } } void destroy() { front = rear = -1; } } Output : .\12JJ1D4001 > javac Program14B_4001.java .\12JJ1D4001 > java Program14B_4001 Enter size of queue 2 1.push 2.pop 3.display 4.destroy Enter your choice :

12JJ1D4001

5.exit

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

41

Advanced Problem Solving 1 Enter data to insert 10 1.push 2.pop 3.display Enter your choice : 1 Enter data to insert 11 1.push 2.pop 3.display Enter your choice : 3 Elements of Queue are 10 11 1.push 2.pop 3.display Enter your choice : 2 data deleted =10 1.push 2.pop 3.display Enter your choice : 3 Elements of Queue are 11 1.push 2.pop 3.display Enter your choice : 5

12JJ1D4001

4.destroy

5.exit

4.destroy

5.exit

4.destroy

5.exit

4.destroy

5.exit

4.destroy

5.exit

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

42

Advanced Problem Solving

12JJ1D4001

12JJ1D4001_15.java Program 15 : Write a java program that uses both stack and queue to test whether the given string is a palindrome. import java.util.Scanner; class Stack { int MAX_SIZE; char stackArr[]; int top; public Stack(int max) { MAX_SIZE = max; stackArr = new char[MAX_SIZE]; top = -1; } public void push(char j) {

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

43

Advanced Problem Solving stackArr[++top] = j; } public char pop() { return stackArr[top--]; } } class Queue { int MAX_SIZE; char queueArr[]; int front, rear; public Queue(int max) { MAX_SIZE = max; queueArr = new char[MAX_SIZE]; front = rear = -1; } public void push(char j) { queueArr[++rear] = j; if (front == -1) front = 0; } public char pop() { char x = queueArr[front]; queueArr[front] = 0; if (front == rear) front = rear = -1; else front++; return x; } } class Program15_4001 { public static void main(String args[]) { int n = 0, count = 0; String givenString = null;

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

44

Advanced Problem Solving char stackPop[], queuePop[]; Scanner sc = new Scanner(System.in); System.out.println("Enter A String"); givenString = sc.nextLine(); n = givenString.length(); Stack stack = new Stack(n); Queue queue = new Queue(n); stackPop = new char[n]; queuePop = new char[n]; for (int i = 0; i < n; i++) stack.push(givenString.charAt(i)); for (int i = 0; i < n; i++) stackPop[i] = stack.pop(); for (int i = 0; i < n; i++) queue.push(stackPop[i]); for (int i = 0; i < n; i++) queuePop[i] = queue.pop(); for (int i = 0; i < n; i++) { if (givenString.charAt(i) == queuePop[i]) { count++; } } if (count == n) System.out.println("Given String Is A Palindrome"); else System.out.println("Given String Is Not A Palindrome"); sc.close(); } } Output : .\12JJ1D4001 > javac Program15_4001.java .\12JJ1D4001 > java Program15_4001 Enter A String hello madam how are you Given String Is Not A Palindrome .\12JJ1D4001 > java Program15_4001 Enter A String

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

45

Advanced Problem Solving hello madam olleh Given String Is A Palindrome

12JJ1D4001

12JJ1D4001_16A.java Program 16 : 16. A) Write a java program to implement ADT for singly linked list. import java.io.*; import java.util.*; class SLLNode2 { int data; SLLNode2 next; SLLNode2(int n) { data = n; next = null; } } class SLLop2 { SLLNode2 head, temp, temp1;

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

46

Advanced Problem Solving SLLop2() { head = null; } void addEnd(int n) { if (head != null) { temp = head; while (temp.next != null) temp = temp.next; temp.next = new SLLNode2(n); temp = temp.next; } else head = new SLLNode2(n); } void addFront(int n) { if (head != null) { temp = new SLLNode2(n); temp.next = head; head = temp; } else head = new SLLNode2(n); } void addAfter(int n, int p) { if (head != null) { temp = head; while (temp.data != p) temp = temp.next; temp1 = new SLLNode2(n); temp1.next = temp.next; temp.next = temp1; temp = temp1; } else head = new SLLNode2(n); } void addBefore(int n, int p) { if (head != null) { temp = head; while (temp.next.data != p) temp = temp.next; temp1 = new SLLNode2(n);

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

47

Advanced Problem Solving temp1.next = temp.next; temp.next = temp1; temp = temp1; } else head = new SLLNode2(n); } void delete(int n) { if (head != null) { if (head.data != n) { temp = head; while (temp.next.data != n) temp = temp.next; temp.next = temp.next.next; } else head = head.next; } else System.out.println("List Empty"); } void display() { if (head != null) { System.out.println(); for (temp = head; temp != null; temp = temp.next) System.out.print(temp.data + "\t"); } else System.out.println("List Empty"); }

12JJ1D4001

} class Program16A_4001 { public static void main(String args[]) { SLLop2 obj = new SLLop2(); while (true) { try { System.out.println("\nMain Menu\n1.AddEnd\t2.AddFront\t 3.AddAfter\t4.AddBefore\t5.Delete\t6.display\t7.exit"); System.out.println("choose ur choice"); Scanner sc = new Scanner(System.in); int ch = sc.nextInt(); switch (ch) { case 1: System.out.println("Enter elemnet to Add");

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

48

Advanced Problem Solving int n1 = sc.nextInt(); obj.addEnd(n1); break; case 2: System.out.println("Enter elemnet to Add"); int n2 = sc.nextInt(); obj.addFront(n2); break; case 3: System.out.println("Enter position element"); int p3 = sc.nextInt(); System.out.println("Enter elemnet to Add"); int n3 = sc.nextInt(); obj.addAfter(n3, p3); break; case 4: System.out.println("Enter position element"); int p4 = sc.nextInt(); System.out.println("Enter elemnet to Add"); int n4 = sc.nextInt(); obj.addBefore(n4, p4); break; case 5: System.out.println("Enter elemnet to delete"); int n5 = sc.nextInt(); obj.delete(n5); break; case 6: obj.display(); break; case 7: System.exit(0); default: System.out.println("Choose Correct Option"); break; } } catch (NullPointerException e) { System.out.println("Element not found"); } }

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

49

Advanced Problem Solving } }

12JJ1D4001

Output : .\12JJ1D4001 > javac Program16A_4001.java .\12JJ1D4001 > java Program16A_4001 Main Menu 1.Add End 2.Add Front 3.Add After choose ur choice 1 Enter elemnet to Add 10 Main Menu 1.Add End 2.Add Front 3.Add After choose ur choice 2 Enter elemnet to Add 7 Main Menu 1.Add End 2.Add Front 3.Add After choose ur choice 3 Enter position element 7 Enter elemnet to Add 8 Main Menu 1.Add End 2.Add Front 3.Add After choose ur choice 4 Enter position element 10 Enter elemnet to Add 9 Main Menu 1.Add End 2.Add Front 3.Add After choose ur choice 6

4.Add Before 5.Delete

6.display

7.exit

4.Add Before 5.Delete

6.display

7.exit

4.Add Before 5.Delete

6.display

7.exit

4.Add Before 5.Delete

6.display

7.exit

4.Add Before 5.Delete

6.display

7.exit

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

50

Advanced Problem Solving

12JJ1D4001

7 8 9 10 Main Menu 1.Add End 2.Add Front choose ur choice 5 Enter elemnet to delete 9 Main Menu 1.Add End 2.Add Front choose ur choice 6 7 8 10 Main Menu 1.Add End 2.Add Front choose ur choice 7

3.Add After

4.Add Before 5.Delete

6.display

7.exit

3.Add After

4.Add Before 5.Delete

6.display

7.exit

3.Add After

4.Add Before 5.Delete

6.display

7.exit

12JJ1D4001_16B.java 16. B) Write a java program to implement ADT for doubly linked list. import java.io.*; import java.util.*; class DLLNode { int data; DLLNode next, prev; DLLNode(int n) { data = n; next = null; prev = null; } } class DLLop { DLLNode head, temp, temp1; DLLop() { head = null;

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

51

Advanced Problem Solving } void addEnd(int el) { if (head != null) { temp = head; while (temp.next != null) temp = temp.next; temp1 = new DLLNode(el); temp.next = temp1; temp1.prev = temp; temp = temp1; } else head = new DLLNode(el); } void addFront(int el) { if (head != null) { temp = new DLLNode(el); head.prev = temp; temp.next = head; head = temp; } else head = new DLLNode(el); } void addAfter(int p, int el) { if (head != null) { temp = head; while (temp.data != p) temp = temp.next; temp1 = new DLLNode(el); temp1.next = temp.next; temp1.prev = temp; temp.next.prev = temp1; temp.next = temp1; } else head = new DLLNode(el); } void addBefore(int p, int el) { if (head != null) { temp = head; while (temp.next.data != p) temp = temp.next;

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

52

Advanced Problem Solving temp1 = new DLLNode(el); temp1.next = temp.next; temp1.prev = temp; temp.next.prev = temp1; temp.next = temp1; } else head = new DLLNode(el); } void delete(int el) { if (head != null) { if (head.data != el) { temp = head; while (temp.next.data != el) temp = temp.next; temp.next = temp.next.next; if (temp.next != null) temp.next.prev = temp; } else { head = head.next; head.prev = null; } } else System.out.println("List Empty"); } void display() { if (head != null) { System.out.println(); for (temp = head; temp != null; temp = temp.next) System.out.print(temp.data + "\t"); } else System.out.println("List Empty"); }

12JJ1D4001

} class Program16B_4001 { public static void main(String args[]) { DLLop obj = new DLLop(); while (true) { try { System.out.println("\nMain Menu\n1.AddEnd\t2.AddFront\t 3.AddAfter\t4.AddBefore\t5.Delete\t6.display\t7.exit");

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

53

Advanced Problem Solving System.out.println("choose ur choice"); Scanner sc = new Scanner(System.in); int ch = sc.nextInt(); switch (ch) { case 1: System.out.println("Enter elemnet to Add"); int n1 = sc.nextInt(); obj.addEnd(n1); break; case 2: System.out.println("Enter elemnet to Add"); int n2 = sc.nextInt(); obj.addFront(n2); break; case 3: System.out.println("Enter position element"); int p3 = sc.nextInt(); System.out.println("Enter element to Add"); int n3 = sc.nextInt(); obj.addAfter(p3, n3); break; case 4: System.out.println("Enter position element"); int p4 = sc.nextInt(); System.out.println("Enter elemnet to Add"); int n4 = sc.nextInt(); obj.addBefore(p4, n4); break; case 5: System.out.println("Enter elemnet to delete"); int n5 = sc.nextInt(); obj.delete(n5); break; case 6: obj.display(); break; case 7: System.exit(0); default: System.out.println("Choose Correct Option");

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

54

Advanced Problem Solving break; } } catch (NullPointerException e) { System.out.println("Element not found"); } } } } Output : .\12JJ1D4001 > javac Program16B_4001.java .\12JJ1D4001 > java Program16B_4001 Main Menu 1.Add End 2.Add Front 3.Add After choose ur choice 1 Enter elemnet to Add 10 Main Menu 1.Add End 2.Add Front 3.Add After choose ur choice 2 Enter elemnet to Add 7 Main Menu 1.Add End 2.Add Front 3.Add After choose ur choice 3 Enter position element 7 Enter element to Add 8 Main Menu 1.Add End 2.Add Front 3.Add After choose ur choice 4 Enter position element 10 Enter elemnet to Add 9

12JJ1D4001

4.Add Before 5.Delete

6.display

7.exit

4.Add Before 5.Delete

6.display

7.exit

4.Add Before 5.Delete

6.display

7.exit

4.Add Before 5.Delete

6.display

7.exit

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

55

Advanced Problem Solving Main Menu 1.Add End 2.Add Front choose ur choice 6 7 8 9 10 Main Menu 1.Add End 2.Add Front choose ur choice 5 Enter elemnet to delete 9 Main Menu 1.Add End 2.Add Front choose ur choice 6 7 8 10 Main Menu 1.Add End 2.Add Front choose ur choice 7 Program 17 : 17. A) Write a java program to implement stack ADT using singly linked list. import java.io.*; import java.util.*; class SLLNode1 { int data; SLLNode1 next; SLLNode1(int n) { data = n; next = null; } } class SLLop1 { SLLNode1 head, temp, temp1;

12JJ1D4001

3.Add After

4.Add Before 5.Delete

6.display

7.exit

3.Add After

4.Add Before 5.Delete

6.display

7.exit

3.Add After

4.Add Before 5.Delete

6.display

7.exit

3.Add After

4.Add Before 5.Delete

6.display

7.exit

12JJ1D4001_17A.java

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

56

Advanced Problem Solving

12JJ1D4001

SLLop1() { head = null; } void push(int n) { if (head != null) { temp = head; while (temp.next != null) temp = temp.next; temp.next = new SLLNode1(n); temp = temp.next; } else head = new SLLNode1(n); System.out.println("Inserted Successfully"); } void pop() { if (head != null) { if (head.next != null) { temp = head; while (temp.next.next != null) temp = temp.next; temp.next = null; } else head = null; System.out.println("Popped Successfully"); } else System.out.println("Stack Underflow"); } void display() { if (head != null) { System.out.println("The Items In The Stack Are : "); for (temp = head; temp != null; temp = temp.next) System.out.print(temp.data + "\t"); System.out.println(); } else System.out.println("List Empty"); }

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

57

Advanced Problem Solving

12JJ1D4001

void topEl() { if (head != null) { temp = head; while (temp.next != null) temp = temp.next; System.out .println("The Top Element In The Stack is : " + temp.data); } else System.out.println("List Empty"); } } class Program17A_4001 { public static void main(String args[]) { SLLop1 obj = new SLLop1(); while (true) { System.out .println("\nMain Menu\n1.Push\t2.Pop\t3.Display\t4.Top Element\t5.exit"); System.out.println("choose ur choice"); Scanner sc = new Scanner(System.in); int ch = sc.nextInt(); switch (ch) { case 1: System.out.println("Enter elemnet to Push"); int n1 = sc.nextInt(); obj.push(n1); break; case 2: obj.pop(); break; case 3: obj.display(); break; case 4: obj.topEl(); break; case 5: System.exit(0);

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

58

Advanced Problem Solving default: System.out.println("Choose Correct Option"); break; } } } }

12JJ1D4001

Output : .\12JJ1D4001 > javac Program17A_4001.java .\12JJ1D4001 > java Program17A_4001 Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit choose ur choice 1 Enter elemnet to Push 10 Inserted Successfully Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit choose ur choice 1 Enter elemnet to Push 11 Inserted Successfully Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit choose ur choice 1 Enter elemnet to Push 12 Inserted Successfully Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit choose ur choice 3 The Items In The Stack Are : 10 11 12

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

59

Advanced Problem Solving Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit choose ur choice 2 Popped Successfully Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit choose ur choice 3 The Items In The Stack Are : 10 11 Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit choose ur choice 4 The Top Element In The Stack is : 11 Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit choose ur choice 5

12JJ1D4001

12JJ1D4001_17B.java 17. B) Write a java program to implement queue ADT using singly linked list. import java.io.*; import java.util.*; class SLLNode { int data; SLLNode next; SLLNode(int n) { data = n; next = null; } } class SLLop { SLLNode head, temp, temp1; SLLop() {

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

60

Advanced Problem Solving head = null;

12JJ1D4001

} void push(int n) { if (head != null) { temp = head; while (temp.next != null) temp = temp.next; temp.next = new SLLNode(n); temp = temp.next; } else head = new SLLNode(n); System.out.println("Inserted Successfully"); } void pop() { if (head != null) { if (head.next != null) { temp = head; head = head.next; } else head = null; System.out.println("Popped Successfully"); } else System.out.println("Queue Underflow"); } void display() { if (head != null) { System.out.println("The Items In The Queue Are : "); for (temp = head; temp != null; temp = temp.next) System.out.print(temp.data + "\t"); System.out.println(); } else System.out.println("Queue Empty"); } void topEl() { if (head != null) { temp = head; while (temp.next != null) temp = temp.next; System.out.println("The Top Element In The Queue is : " + temp.data); } else

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

61

Advanced Problem Solving System.out.println("Queue Empty"); } } class Program17B_4001 { public static void main(String args[]) { SLLop obj = new SLLop(); while (true) { System.out.println("\nMain Menu\n1.Push\t2.Pop\t3.Display\t 4.TopElement\t5.exit"); System.out.println("choose ur choice"); Scanner sc = new Scanner(System.in); int ch = sc.nextInt(); switch (ch) { case 1: System.out.println("Enter elemnet to Push"); int n1 = sc.nextInt(); obj.push(n1); break; case 2: obj.pop(); break; case 3: obj.display(); break; case 4: obj.topEl(); break; case 5: System.exit(0); default: System.out.println("Choose Correct Option"); break; } } } }

12JJ1D4001

Output : .\12JJ1D4001 > javac Program17B_4001.java


JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

62

Advanced Problem Solving .\12JJ1D4001 > java Program17B_4001 Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit choose ur choice 1 Enter elemnet to Push 10 Inserted Successfully Main Menu 1.Push 2.Pop 3.Display choose ur choice 1 Enter elemnet to Push 11 Inserted Successfully Main Menu 1.Push 2.Pop 3.Display choose ur choice 1 Enter elemnet to Push 12 Inserted Successfully

12JJ1D4001

4.Top Element 5.exit

4.Top Element 5.exit

Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit choose ur choice 3 The Items In The Queue Are : 10 11 12 Main Menu 1.Push 2.Pop 3.Display choose ur choice 2 Popped Successfully Main Menu 1.Push 2.Pop 3.Display

4.Top Element 5.exit

4.Top Element 5.exit

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

63

Advanced Problem Solving choose ur choice 3 The Items In The Queue Are : 11 12 Main Menu 1.Push 2.Pop 3.Display 4.Top Element 5.exit choose ur choice 4 The Top Element In The Queue is : 12 Main Menu 1.Push 2.Pop 3.Display choose ur choice 5

12JJ1D4001

4.Top Element 5.exit

12JJ1D4001_18A.java Program 18 : 18.A) Write a java program to implement the deque (double ended queue) ADT using arrays. class Dequeue { int max = 8, x, y, l = 0, r = max - 1, i, j, ch; int a[] = new int[50]; void insleft(int ele) { i = l - 1; while (i >= 0) a[i + 1] = a[i--]; a[0] = ele; l++; } void rmleft() { i = 0; i--; while (i < l)

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

64

Advanced Problem Solving a[i++] = a[i + 1]; a[i] = 0; } void insright(int ele) { j = r + 1; while (j > r && j < max) a[j - 1] = a[j++]; a[max - 1] = ele; r--; } void rmright() { j = max - 1; while (j > r) a[j--] = a[j - 1]; a[j] = 0; r++; } void show() { System.out.println("left q"); for (x = r + 1; x > 0; x--) System.out.println(a[x]); System.out.println("right q"); for (x = r + 1; x < max; x++) System.out.println(a[x]); } } class Program18A_4001 { public static void main(String args[]) { Dequeue d = new Dequeue(); d.insleft(10); d.insleft(12); d.insleft(13); d.insleft(14); d.insright(20); d.insright(21); d.insright(22); d.insright(23); d.rmright(); d.show(); System.out.println("Hello World!");

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

65

Advanced Problem Solving } } Output : .\12JJ1D4001 > javac Program18A_4001.java .\12JJ1D4001 > java Program18A_4001 left q 10 12 0 12 13 right q 10 20 21 Hello World!

12JJ1D4001

12JJ1D4001_18B.java 18.B) Write a java program to implement the deque (double ended queue) ADT using linked lists. public class Program18_4001 { public class DequeNode { DequeNode prev; Object data; DequeNode next; DequeNode(Object item) { data = item;

} prite DequeNode first, last; private int count; public void addFirst(Object item) { if (isEmpty()) first = last = new DequeNode(item); else { DequeNode tmp = new DequeNode(item); tmp.next = first;

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

66

Advanced Problem Solving first.prev = tmp; first = tmp; count++;

12JJ1D4001

} public void addLast(Object item) { if (isEmpty()) first = last = new DequeNode(item); else { DequeNode tmp = new DequeNode(item); tmp.prev = last; last.next = tmp; last = tmp; } count++; } public Object removeFirst() { if (isEmpty()) { System.out.println("Deque is empty"); return null; } else { Object item = first.data; first = first.next; first.prev = null; count--; return item; } } public Object removeLast() { if (isEmpty()) { System.out.println("Deque is empty"); return null; } else { Object item = last.data; last = last.prev; last.next = null; count--; return item; } } public Object getFirst() {

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

67

Advanced Problem Solving if (!isEmpty()) return (first.data); else return null; } public Object getLast() { if (!isEmpty()) return (last.data); else return null; } public boolean isEmpty() { return (count == 0); } public int size() { return (count); } public void display() { DequeNode p = first; System.out.print("Deque: [ "); while (p != null) { System.out.print(p.data + " "); p = p.next; } System.out.println("]"); } public static void main(String args[]) { Program18_4001 dq = new Program18_4001(); System.out.println("removeFirst():" + dq.removeFirst()); dq.addFirst('A'); dq.addFirst('B'); dq.addFirst('C'); dq.display(); dq.addLast('D'); dq.addLast('E'); System.out.println("getFirst():" + dq.getFirst()); System.out.println("getLast():" + dq.getLast()); dq.display(); System.out.println("removeFirst():" + dq.removeFirst());

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

68

Advanced Problem Solving System.out.println("removeLast():" + dq.removeLast()); dq.display(); System.out.println("size():" + dq.size()); } } Output : .\12JJ1D4001 > javac Program18B_4001.java .\12JJ1D4001 > java Program18B_4001 Deque is empty removeFirst():null Deque: [ C B A ] getFirst():C getLast():E Deque: [ C B A D E ] removeFirst():C removeLast():E Deque: [ B A D ] size():3

12JJ1D4001

12JJ1D4001_19.java Program 19 : Write a java program to implement circular queue ADT using an array. import java.util.Scanner; public class Program19_4001 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter size of queue"); QueueOs q = new QueueOs(sc.nextInt()); int ch; do { System.out.println("1.push\t2.pop\t3.display\t4.destroy\t5.exit"); System.out.println("Enter your choice :"); ch = sc.nextInt(); switch (ch) { case 1: System.out.println("Enter data to insert");

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

69

Advanced Problem Solving int x = sc.nextInt(); q.push(x); break; case 2: if (q.isEmpty()) System.out.println("Queue underflow"); else { int z = q.pop(); System.out.println("data deleted =" + z); q.push(z); } break; case 3: q.display(); break; case 4: q.destroy(); break; case 5: break; default: System.out.println("Wrong Choice"); } } while (ch != 5); } } class QueueOs { int a[]; int front, rear; QueueOs(int size) { a = new int[size]; front = rear = -1; } void push(int x) { int p; p = (rear + 1) % a.length;

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

70

Advanced Problem Solving

12JJ1D4001

if (p == front) System.out.println("Queue Overflow "); else { rear = p; a[rear] = x; if (front == -1) front = 0; } } boolean isEmpty() { if (front == -1) return true; else return false; } int pop() { int x = a[front]; if (front == rear) front = rear = -1; else front = (front + 1) % a.length; return x; } void display() { if (front == -1) System.out.println("Queue underflow"); else { System.out.println("Elements of Queue are"); int i = front; while (i != rear) { System.out.print(a[i] + "\t"); i = (i + 1) % a.length; } System.out.println(a[i]); }

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

71

Advanced Problem Solving } void destroy() { front = rear = -1; } } Output : .\12JJ1D4001 > javac Program19_4001.java .\12JJ1D4001 > java Program19_4001 Enter size of queue 3 1.push 2.pop 3.display 4.destroy Enter your choice : 1 Enter data to insert 10 1.push 2.pop 3.display 4.destroy Enter your choice : 1 Enter data to insert 11 1.push 2.pop 3.display 4.destroy Enter your choice : 1 Enter data to insert 12 1.push 2.pop 3.display 4.destroy Enter your choice : 1 Enter data to insert 14 Queue Overflow 1.push 2.pop 3.display 4.destroy Enter your choice : 3 Elements of Queue are 10 11 12 1.push 2.pop 3.display 4.destroy Enter your choice :

12JJ1D4001

5.exit

5.exit

5.exit

5.exit

5.exit

5.exit

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

72

Advanced Problem Solving 2 data deleted =10 1.push 2.pop 3.display Enter your choice : 3 Elements of Queue are 11 12 10 1.push 2.pop 3.display Enter your choice : 2 data deleted =11 1.push 2.pop 3.display Enter your choice : 3 Elements of Queue are 12 10 11 1.push 2.pop 3.display Enter your choice : 5

12JJ1D4001

4.destroy

5.exit

4.destroy

5.exit

4.destroy

5.exit

4.destroy

5.exit

12JJ1D4001_20A.java Program 20 : 20. A) Write a java program that use both recursive and non-recusive functions for implementing linear search method. class Program20A_4001 { static int[] a = { 89, 45, 175, 7, 50, 43, 126, 90 }; static int key = 50; public static void main(String args[]) { System.out.println("Using Iterative Linear Search :"); if (linearSearch()) System.out.println(key + " found in the list"); else System.out.println(key + " not found in the list"); System.out.println("Using Recursive Linear Search :"); if (ReclinearSearch(a.length - 1)) System.out.println(key + " found in the list"); else System.out.println(key + " not found in the list"); } static boolean linearSearch() { for (int i = 0; i < a.length; i++)

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

73

Advanced Problem Solving if (key == a[i]) return true; return false; } static boolean ReclinearSearch(int n) { if (n < 0) return false; if (key == a[n]) return true; else return ReclinearSearch(n - 1); } Output : .\12JJ1D4001 > javac Program20A_4001.java .\12JJ1D4001 > java Program20A_4001 Using Iterative Linear Search : 50 found in the list Using Recursive Linear Search : 50 found in the list

12JJ1D4001

12JJ1D4001_20B.java 20.B) Write a java program that use both recursive and non-recusive functions for implementing binary search method. class Program20B_4001 { static Object[] a = { "AP", "KA", "MH", "MP", "OR", "TN", "UP", "WB" }; static Object key = "KA"; public static void main(String args[]) { System.out.println("Using Iterative Binary Search :"); if (binarySearch()) System.out.println(key + " found in the list"); else System.out.println(key + " not found in the list"); System.out.println("Using Recursive Binary Search :"); if (recBinarySearch(0, a.length - 1)) System.out.println(key + " found in the list"); else System.out.println(key + " not found in the list"); } static boolean binarySearch() { int c, mid, low = 0, high = a.length - 1;

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

74

Advanced Problem Solving while (low <= high) { mid = (low + high) / 2; c = ((Comparable) key).compareTo(a[mid]); if (c < 0) high = mid - 1; else if (c > 0) low = mid + 1; else return true; } return false; } static boolean recBinarySearch(int low, int high) { if (low > high) return false; int mid = (low + high) / 2; int c = ((Comparable) key).compareTo(a[mid]); if (c < 0) return recBinarySearch(low, mid - 1); else if (c > 0) return recBinarySearch(mid + 1, high); else return true; } } Output : .\12JJ1D4001 > javac Program20B_4001.java .\12JJ1D4001 > java Program20B_4001 Using Iterative Binary Search : KA found in the list Using Recursive Binary Search : KA found in the list

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

75

Advanced Problem Solving

12JJ1D4001

12JJ1D4001_21.java Program 21 : Write a java program that use recursive and non-recursive functions to traverse the given binary tree in a) Preorder b)Inorder c)Postorder class Node { Object data; Node left; Node right; Node(Object d) { data = d; } } class BinaryTree { Object tree[]; int maxSize; java.util.Stack<Node> stk = new java.util.Stack<Node>();

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

76

Advanced Problem Solving BinaryTree(Object a[], int n) { maxSize = n; tree = new Object[maxSize]; for (int i = 0; i < maxSize; i++) tree[i] = a[i]; } public Node buildTree(int index) { Node p = null; if (tree[index] != null) { p = new Node(tree[index]); p.left = buildTree(2 * index + 1); p.right = buildTree(2 * index + 2); } return p; } public void inorder(Node p) { if (p != null) { inorder(p.left); System.out.print(p.data + " "); inorder(p.right); } } public void preorder(Node p) { if (p != null) { System.out.print(p.data + " "); preorder(p.left); preorder(p.right); } } public void postorder(Node p) { if (p != null) { postorder(p.left); postorder(p.right); System.out.print(p.data + " "); } } public void preorderIterative(Node p) { if (p == null) { System.out.println("Tree is empty"); return;

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

77

Advanced Problem Solving } stk.push(p); while (!stk.isEmpty()) { p = stk.pop(); if (p != null) { System.out.print(p.data + " "); stk.push(p.right); stk.push(p.left); } } } public void inorderIterative(Node p) { if (p == null) { System.out.println("Tree is empty"); return; } while (!stk.isEmpty() || p != null) { if (p != null) { stk.push(p); p = p.left; } else { p = stk.pop(); System.out.print(p.data + " "); p = p.right; } } } public void postorderIterative(Node p) { if (p == null) { System.out.println("Tree is empty"); return; } Node tmp = p; while (p != null) { while (p.left != null) { stk.push(p); p = p.left; } while (p != null && (p.right == null || p.right == tmp)) {

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

78

Advanced Problem Solving System.out.print(p.data + " "); tmp = p; if (stk.isEmpty()) return; p = stk.pop(); } stk.push(p); p = p.right; } } } class Program21_4001 { public static void main(String args[]) { Object arr[] = { 'E', 'C', 'G', 'A', 'D', 'F', 'H', null, 'B', null, null, null, null, null, null, null, null, null, null }; BinaryTree t = new BinaryTree(arr, arr.length); Node root = t.buildTree(0); System.out.print("\n Recursive Binary Tree Traversals:"); System.out.print("\n inorder: "); t.inorder(root); System.out.print("\n preorder: "); t.preorder(root); System.out.print("\n postorder: "); t.postorder(root); System.out.print("\n Non-recursive Binary Tree Traversals:"); System.out.print("\n inorder: "); t.inorderIterative(root); System.out.print("\n preorder: "); t.preorderIterative(root); System.out.print("\n postorder: "); t.postorderIterative(root); } }

12JJ1D4001

Output : .\12JJ1D4001 > javac Program21_4001.java

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

79

Advanced Problem Solving .\12JJ1D4001 > java Program21_4001 Recursive Binary Tree Traversals: inorder: A B C D E F G H preorder: E C A B D G F H postorder: B A D C F H G E Non-recursive Binary Tree Traversals: inorder: A B C D E F G H preorder: E C A B D G F H postorder: B A D C F H G E

12JJ1D4001

12JJ1D4001_22A.java Program 22 : 22. A) Write a java program for implementing the following sorting methods. a)Bubble Sort b)Selection Sort c)Insertion Sort d)Quick Sort. public class Program22A_4001 { static void bubbleSort(int[] a) { int i, pass, exch, n = a.length; int tmp; for (pass = 0; pass < n; pass++) { exch = 0; for (i = 0; i < n - pass - 1; i++) if (((Comparable) a[i]).compareTo(a[i + 1]) > 0) { tmp = a[i]; a[i] = a[i + 1]; a[i + 1] = tmp; exch++; } if (exch == 0)

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

80

Advanced Problem Solving return; } } static void selectionSort(int a[]) { int n = a.length; for (int pass = 0; pass < n - 1; pass++) { int min = pass; for (int i = pass + 1; i < n; i++) if (a[i] < a[min]) min = i; if (min != pass) { int tmp = a[min]; a[min] = a[pass]; a[pass] = tmp; } } } static void insertionSort(int a[]) { int i, j, n = a.length; int item; for (j = 1; j < n; j++) { item = a[j]; i = j - 1; while (i >= 0 && ((Comparable) item).compareTo(a[i]) < 0) { a[i + 1] = a[i]; i = i - 1; } a[i + 1] = item; } } static void quickSort(int a[], int left, int right) { int newleft = left, newright = right; int amid, tmp; amid = a[(left + right) / 2]; do {

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

81

Advanced Problem Solving while ((a[newleft] < amid) && (newleft < right)) newleft++; while ((amid < a[newright]) && (newright > left)) newright--; if (newleft <= newright) { tmp = a[newleft]; a[newleft] = a[newright]; a[newright] = tmp; newleft++; newright--; } } while (newleft <= newright); if (left < newright) quickSort(a, left, newright); if (newleft < right) quickSort(a, newleft, right); } static void display(int a[]) { for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); } public static void main(String[] args) { int[] arr = { 98, 54, 130, 74, 30, 150, 126, 120 }; System.out.print("\n Unsorted array: "); display(arr); bubbleSort(arr); System.out.print("\n Sorted array Using Bubble Sort : "); display(arr); selectionSort(arr); System.out.print("\n Sorted array Using Selection Sort : "); display(arr); insertionSort(arr); System.out.print("\n Sorted array Using Insertion Sort : "); display(arr); quickSort(arr, 0, arr.length - 1); System.out.print("\n Sorted array Using Bubble Sort : "); display(arr); }

12JJ1D4001

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

82

Advanced Problem Solving

12JJ1D4001

Output : .\12JJ1D4001 > javac Program22A_4001.java .\12JJ1D4001 > java Program22A_4001 Unsorted array: 98 54 130 74 30 150 126 120 Sorted array Using Bubble Sort : 30 54 74 98 120 126 130 150 Sorted array Using Selection Sort : 30 54 74 98 120 126 130 150 Sorted array Using Insertion Sort : 30 54 74 98 120 126 130 150 Sorted array Using Bubble Sort : 30 54 74 98 120 126 130 150

12JJ1D4001_22B.java 22. B) Write a java program to implement merge sort. class MergeSort { int[] a; int[] tmp; MergeSort(int[] arr) { a = arr; tmp = new int[a.length]; } void msort() { sort(0, a.length - 1); } void sort(int left, int right) { if (left < right) { int mid = (left + right) / 2; sort(left, mid); sort(mid + 1, right);

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

83

Advanced Problem Solving merge(left, mid, right); } } void merge(int left, int mid, int right) { int i = left; int j = left; int k = mid + 1; while (j <= mid && k <= right) { if (a[j] < a[k]) tmp[i++] = a[j++]; else tmp[i++] = a[k++]; } while (j <= mid) tmp[i++] = a[j++]; for (i = left; i < k; i++) a[i] = tmp[i]; } } class Program22B_4001 { public static void main(String[] args) { int[] arr = { 75, 40, 10, 90, 50, 95, 55, 15, 65 }; MergeSort ms = new MergeSort(arr); System.out.println("Unsorted array:"); for (int i = 0; i < arr.length; i++) System.out.print(arr[i] + " "); System.out.println(); ms.msort(); System.out.println("Sorted array Using Merge Sort :"); for (int i = 0; i < arr.length; i++) System.out.print(arr[i] + " "); } }

12JJ1D4001

Output : .\12JJ1D4001 > javac Program22B_4001.java

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

84

Advanced Problem Solving .\12JJ1D4001 > java Program22B_4001 Unsorted array: 98 54 130 74 30 150 126 120 75 40 10 90 50 95 55 15 65 Sorted array Using Merge Sort : 10 15 40 50 55 65 75 90 95

12JJ1D4001

12JJ1D4001_22C.java 22. C) Write a java program to implement heap sort. class Heap { int[] a; int maxSize; int currentSize; public Heap(int m) { maxSize = m; currentSize = 0; a = new int[maxSize]; } public boolean insert(int key) { if (currentSize == maxSize) return false; a[currentSize] = key; moveUp(currentSize++); return true; }

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

85

Advanced Problem Solving

12JJ1D4001

public void moveUp(int index) { int parent = (index - 1) / 2; int bottom = a[index]; while (index > 0 && a[parent] < bottom) { a[index] = a[parent]; index = parent; parent = (parent - 1) / 2; } a[index] = bottom; } public int remove() { if (isEmpty()) { System.out.println("Heap is empty"); return -1; } int root = a[0]; a[0] = a[--currentSize]; moveDown(0); return root; } public void moveDown(int index) { int largerChild; int top = a[index]; while (index < currentSize / 2) { int leftChild = 2 * index + 1; int rightChild = 2 * index + 2; if (rightChild < currentSize && a[leftChild] < a[rightChild]) largerChild = rightChild; else largerChild = leftChild; if (top >= a[largerChild]) break; a[index] = a[largerChild]; index = largerChild; } a[index] = top; }

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

86

Advanced Problem Solving

12JJ1D4001

public boolean isEmpty() { return currentSize == 0; } public void displayHeap(int[] a) { for (int i = 0; i < maxSize; i++) System.out.print(" " + a[i] + " "); } } class Program22C_4001 { public static void main(String[] args) { int[] arr = { 50, 20, 30, 10, 40, 70, 60 }; Heap h = new Heap(arr.length); System.out.println("\nUnsorted array: "); h.displayHeap(arr); for (int i = 0; i < arr.length; i++) h.insert(arr[i]); for (int i = arr.length - 1; i >= 0; i--) arr[i] = h.remove(); System.out.println("\nSorted array using Heap sort : "); h.displayHeap(arr); } } Output : .\12JJ1D4001 > javac Program22C_4001.java .\12JJ1D4001 > java Program22C_4001 Unsorted array: 50 20 30 10 40 70 60 Sorted array using Heap sort : 10 20 30 40 50 60 70

JNTUH COLLEGE OF ENGINEERING, NACHUPALLY (KONDAGATTU), KARIMNAGAR

87

También podría gustarte