Strings and Arrays


Duplicates:-
DuplicateInList.java
package Duplicates;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class DuplicateInList {
                public static void main(String[] args) {
                                List<String> list = new LinkedList<String>();
                                for (int i = 0; i < 10; i++) {
                                                list.add(String.valueOf(i));
                                }
                                for (int i = 0; i < 5; i++) {
                                                list.add(String.valueOf(i));
                                }

                                System.out.println("My List : " + list);
                                System.out.println("\nHere are the duplicate elements from list : "
                                                                + findDuplicates(list));
                }

                public static Set<String> findDuplicates(
                                                List<String> listContainingDuplicates) {

                                final Set<String> setToReturn = new HashSet<String>();
                                final Set<String> set1 = new HashSet<String>();

                                for (String yourInt : listContainingDuplicates) {
                                                if (!set1.add(yourInt)) {
                                                                setToReturn.add(yourInt);
                                                }
                                }
                                return setToReturn;
                }
}
o/p:-
My List : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]

Here are the duplicate elements from list : [3, 2, 1, 0, 4]

DuplicatesInArray.java
package Duplicates;
//Java Program To Find Duplicate Elements In An Array Using Brute Force Method :

public class DuplicatesInArray {
     public static void main(String[] args) {
           String[] strArray = { "abc", "def", "mno", "xyz", "pqr", "xyz", "def" };

           for (int i = 0; i < strArray.length - 1; i++) {
                for (int j = i + 1; j < strArray.length; j++) {
                     if ((strArray[i].equals(strArray[j])) && (i != j)) {
                           System.out.println("Duplicate Element is : " + strArray[j]);
                     }
                }
           }//for
     }//main
}

o/p:-
Duplicate Element is : def
Duplicate Element is : xyz

FindDuplicatesInString.java
package Duplicates;
//Java program to count all duplicates from string using hashing

public class FindDuplicatesInString {
     static final int NO_OF_CHARS = 256;

     /* Fills count array with frequency of characters */
     static void fillCharCounts(String str, int[] count) {
           for (int i = 0; i < str.length(); i++)
                count[str.charAt(i)]++;
     }

     /* Print duplicates present in the passed string */
     static void printDups(String str) {
           // Create an array of size 256 and fill count of every character in it
           int count[] = new int[NO_OF_CHARS];
           fillCharCounts(str, count);

           for (int i = 0; i < NO_OF_CHARS; i++)
                if (count[i] > 1)
                     System.out.printf("%c,  count = %d \n", i, count[i]);

     }

     // Driver Method
     public static void main(String[] args) {
           String str = "test string";
           printDups(str);
     }
}

o/p:-
s,  count = 2
t,  count = 3

RemoveDuplicates.java
package Duplicates;

import java.util.LinkedHashSet;

//Java prigram to remove duplicates
public class RemoveDuplicates {
     /*
      * Function removes duplicate characters from the string This function work
      * in-place
      */
     void removeDuplicates(String str) {
           LinkedHashSet<Character> lhs = new LinkedHashSet<>();
           for (int i = 0; i < str.length(); i++)
                lhs.add(str.charAt(i));

           // print string after deleting duplicate elements
           for (Character ch : lhs)
                System.out.print(ch);
     }

     /* Driver program to test removeDuplicates */
     public static void main(String args[]) {
           String str = "geeksforgeeks";
           RemoveDuplicates r = new RemoveDuplicates();
           r.removeDuplicates(str);
     }
}

o/p:-
geksfor
Elements:-
CommonElement.java
package Elements;

import java.util.HashSet;
//finding common elements in two string arrays:-
public class CommonElement {
     public static void main(String[] args) {
           String[] s1 = { "ONE", "TWO", "THREE", "FOUR", "FIVE", "FOUR" };

           String[] s2 = { "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "FOUR" };

           HashSet<String> set = new HashSet<String>();

           for (int i = 0; i < s1.length; i++) {
                for (int j = 0; j < s2.length; j++) {
                     if (s1[i].equals(s2[j])) {
                           set.add(s1[i]);
                     }
                }
           }

           System.out.println(set); // OUTPUT : [THREE, FOUR, FIVE]
     }
}

o/p:-
[THREE, FOUR, FIVE]

CommonElements1.java
package Elements;

import java.util.Arrays;
import java.util.HashSet;
//finding common elements in two integer arrays:-
public class CommonElements1 {
                public static void main(String[] args)
    {
        Integer[] i1 = {1, 2, 3, 4, 5, 4};

        Integer[] i2 = {3, 4, 5, 6, 7, 4};

        HashSet<Integer> set1 = new HashSet<>(Arrays.asList(i1));

        HashSet<Integer> set2 = new HashSet<>(Arrays.asList(i2));

        set1.retainAll(set2);

        System.out.println(set1);     //Output : [3, 4, 5]
    }
}
o/p:-
[3, 4, 5]

CrunchifyHashmapToArrayList.java
package Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

//Converting HashMap to ArrayList:-
public class CrunchifyHashmapToArrayList {
                /**
                 * @param args
                 */
                public static void main(String... args) {
                                HashMap<String, Integer> companyDetails = new HashMap<String, Integer>();

                                // create hashmap with keys and values (CompanyName, #Employees)
                                companyDetails.put("eBay", 4444);
                                companyDetails.put("Paypal", 5555);
                                companyDetails.put("IBM", 6666);
                                companyDetails.put("Google", 7777);
                                companyDetails.put("Yahoo", 8888);

                                System.out.println("==> Size of companyDetails Map: "
                                                                + companyDetails.size());
                                Iterator it = companyDetails.entrySet().iterator();
                                while (it.hasNext()) {
                                                Map.Entry pairs = (Map.Entry) it.next();
                                                System.out.println(pairs.getKey() + " = " + pairs.getValue());
                                }

                                // Converting HashMap keys into ArrayList
                                List<String> keyList = new ArrayList<String>(companyDetails.keySet());
                                System.out.println("\n==> Size of Key list: " + keyList.size());

                                for (String temp : keyList) {
                                                System.out.println(temp);
                                }

                                // Converting HashMap Values into ArrayList
                                List<Integer> valueList = new ArrayList<Integer>(
                                                                companyDetails.values());
                                System.out.println("\n==> Size of Value list: " + valueList.size());
                                for (Integer temp : valueList) {
                                                System.out.println(temp);
                                }

                                List<Entry> entryList = new ArrayList<Entry>(companyDetails.entrySet());
                                System.out.println("\n==> Size of Entry list: " + entryList.size());
                                for (Entry temp : entryList) {
                                                System.out.println(temp);
                                }
                }
}

o/p:-
==> Size of companyDetails Map: 5
IBM = 6666
Yahoo = 8888
Google = 7777
Paypal = 5555
eBay = 4444

==> Size of Key list: 5
IBM
Yahoo
Google
Paypal
eBay

==> Size of Value list: 5
6666
8888
7777
5555
4444

==> Size of Entry list: 5
IBM=6666
Yahoo=8888
Google=7777
Paypal=5555
eBay=4444

CrunchifyStringReplaceDelete.java
package Elements;

public class CrunchifyStringReplaceDelete {
     public static void main(String[] args) {
           System.out.println("Output for replaceAllChar(): "
                     + replaceAllChar("crunchify.com - Web Development", "e", "*"));
           System.out.println("Output for deleteAllNonDigit(): "
                     + deleteAllNonDigit("#21sadfs23$&%^(!9@!"));
           System.out.println("Output for replaceCharAt(): "
                     + replaceCharAt("eBay Google Paypal", 10, '$'));
           System.out.println("Output for removeChar(): "
                     + removeChar("I_am_Mohammed", '_'));
           System.out.println("Output for removeCharAt(): "
                     + removeCharAt("eBay Google Paypal", 5));
     }

     private static String removeCharAt(String s, int i) {
           StringBuffer buf = new StringBuffer(s.length() - 1);
           buf.append(s.substring(0, i)).append(s.substring(i + 1));
           return buf.toString();
     }

     private static String removeChar(String s, char c) {
           StringBuffer buf = new StringBuffer(s.length());
           buf.setLength(s.length());
           int current = 0;
           for (int i = 0; i < s.length(); i++) {
                char cur = s.charAt(i);
                if (cur != c)
                     buf.setCharAt(current++, cur);
           }
           return buf.toString();
     }

     private static String replaceCharAt(String s, int i, char c) {
           StringBuffer buf = new StringBuffer(s);
           buf.setCharAt(i, c);
           return buf.toString();
     }

     private static String deleteAllNonDigit(String s) {
           String temp = s.replaceAll("\\D", "");
           return temp;
     }

     public static String replaceAllChar(String s, String f, String r) {
           String temp = s.replace(f, r);
           return temp;
     }
}

o/p:-
Output for replaceAllChar(): crunchify.com - W*b D*v*lopm*nt
Output for deleteAllNonDigit(): 21239
Output for replaceCharAt(): eBay Googl$ Paypal
Output for removeChar(): IamMohammed_
IndexOfExample.java
package Elements;

import java.util.ArrayList;
//finding index of elements for ArrayList:-
public class IndexOfExample {
     public static void main(String[] args) {
           ArrayList<String> al = new ArrayList<String>();
           al.add("AB");
           al.add("CD");
           al.add("EF");
           al.add("GH");
           al.add("IJ");
           al.add("KL");
           al.add("MN");

           System.out.println("Index of 'AB': " + al.indexOf("AB"));
           System.out.println("Index of 'KL': " + al.indexOf("KL"));
           System.out.println("Index of 'AA': " + al.indexOf("AA"));
           System.out.println("Index of 'EF': " + al.indexOf("EF"));
     }
}

o/p:-
Index of 'AB': 0
Index of 'KL': 5
Index of 'AA': -1
Index of 'EF': 2

RemoveAllSpace.java
package Elements;

public class RemoveAllSpace {
     public static void main(String[] args) {
           String str = "India     Is My    Country";
           // 1st way
           String noSpaceStr = str.replaceAll("\\s", ""); // using built in method
           System.out.println(noSpaceStr);
           // 2nd way
           char[] strArray = str.toCharArray();
           StringBuffer stringBuffer = new StringBuffer();
           for (int i = 0; i < strArray.length; i++) {
                if ((strArray[i] != ' ') && (strArray[i] != '\t')) {
                     stringBuffer.append(strArray[i]);
                }
           }
           String noSpaceStr2 = stringBuffer.toString();
           System.out.println(noSpaceStr2);
     }
}

o/p:-
IndiaIsMyCountry
IndiaIsMyCountry

RepeatElement.java
package Elements;
//repeated elements in integer Array:-
public class RepeatElement {
     void printRepeating(int arr[], int size) {
           int i, j;
           System.out.println("Repeated Elements are :");
           for (i = 0; i < size; i++) {
                for (j = i + 1; j < size; j++) {
                     if (arr[i] == arr[j])
                           System.out.print(arr[i] + " ");
                }
           }
     }

     public static void main(String[] args) {
           RepeatElement repeat = new RepeatElement();
           int arr[] = { 10, 20, 20, 10, 20, 301 };
           int arr_size = arr.length;
           repeat.printRepeating(arr, arr_size);
     }
}

o/p:-
Repeated Elements are :
10 20 20 20
Test.java
package Elements;

import java.util.LinkedList;
//Java code for Linked List implementation

public class Test {
     public static void main(String args[]) {
           // Creating object of class linked list
           LinkedList<String> object = new LinkedList<String>();

           // Adding elements to the linked list
           object.add("A");
           object.add("B");
           object.addLast("C");
           object.addFirst("D");
           object.add(2, "E");
           object.add("F");
           object.add("G");
           System.out.println("Linked list : " + object);

           // Removing elements from the linked list
           object.remove("B");
           object.remove(3);
           object.removeFirst();
           object.removeLast();
           System.out.println("Linked list after deletion: " + object);

           // Finding elements in the linked list
           boolean status = object.contains("E");

           if (status)
                System.out.println("List contains the element 'E' ");
           else
                System.out.println("List doesn't contain the element 'E'");

           // Number of elements in the linked list
           int size = object.size();
           System.out.println("Size of linked list = " + size);

           // Get and set elements from linked list
           Object element = object.get(2);
           System.out.println("Element returned by get() : " + element);
           object.set(2, "Y");
           System.out.println("Linked list after change : " + object);
     }
}

o/p:-
Linked list : [D, A, E, B, C, F, G]
Linked list after deletion: [A, E, F]
List contains the element 'E'
Size of linked list = 3
Element returned by get() : F
Linked list after change : [A, E, Y]

Stacks.java
package Elements;

import java.util.Stack;

public class Stacks {
     // Pushing element on the top of the stack
           static void stack_push(Stack<Integer> stack) {
                for (int i = 0; i < 5; i++) {
                     stack.push(i);
                }
           }

           // Popping element from the top of the stack
           static void stack_pop(Stack<Integer> stack) {
                System.out.println("Pop :");

                for (int i = 0; i < 5; i++) {
                     Integer y = (Integer) stack.pop();
                     System.out.println(y);
                }
           }

           // Displaying element on the top of the stack
           static void stack_peek(Stack<Integer> stack) {
                Integer element = (Integer) stack.peek();
                System.out.println("Element on stack top : " + element);
           }

           // Searching element in the stack
           static void stack_search(Stack<Integer> stack, int element) {
                Integer pos = (Integer) stack.search(element);

                if (pos == -1)
                     System.out.println("Element not found");
                else
                     System.out.println("Element is found at position " + pos);
           }

           public static void main(String[] args) {
                Stack<Integer> stack = new Stack<Integer>();

                stack_push(stack);
                stack_pop(stack);
                stack_push(stack);
                stack_peek(stack);
                stack_search(stack, 2);
                stack_search(stack, 6);
           }
}

o/p:-
Pop :
4
3
2
1
0
Element on stack top : 4
Element is found at position 3
Element not found

Vectors.java
package Elements;

import java.util.Vector;

public class Vectors {
     public static void main(String[] arg) {

           // create default vector
           Vector v = new Vector();

           v.add(1);
           v.add(2);
           v.add("geeks");
           v.add("forGeeks");
           v.add(3);

           System.out.println("Vector is " + v);

     }
}

o/p:-
Vector is [1, 2, geeks, forGeeks, 3]

TrieTest.java
package Elements;

/*
 *  Java Program to Implement Trie
 */
/*
 *  Java Program to Implement Trie
 */

import java.util.LinkedList;
import java.util.Scanner;

class TrieNode {
     char content;
     boolean isEnd;
     int count;
     LinkedList<TrieNode> childList;

     /* Constructor */
     public TrieNode(char c) {
           childList = new LinkedList<TrieNode>();
           isEnd = false;
           content = c;
           count = 0;
     }

     public TrieNode subNode(char c) {
           if (childList != null)
                for (TrieNode eachChild : childList)
                     if (eachChild.content == c)
                           return eachChild;
           return null;
     }
}

class Trie {
     private TrieNode root;

     /* Constructor */
     public Trie() {
           root = new TrieNode(' ');
     }

     /* Function to insert word */
     public void insert(String word) {
           if (search(word) == true)
                return;
           TrieNode current = root;
           for (char ch : word.toCharArray()) {
                TrieNode child = current.subNode(ch);
                if (child != null)
                     current = child;
                else {
                     current.childList.add(new TrieNode(ch));
                     current = current.subNode(ch);
                }
                current.count++;
           }
           current.isEnd = true;
     }

     /* Function to search for word */
     public boolean search(String word) {
           TrieNode current = root;
           for (char ch : word.toCharArray()) {
                if (current.subNode(ch) == null)
                     return false;
                else
                     current = current.subNode(ch);
           }
           if (current.isEnd == true)
                return true;
           return false;
     }

     /* Function to remove a word */
     public void remove(String word) {
           if (search(word) == false) {
                System.out.println(word + " does not exist in trie\n");
                return;
           }
           TrieNode current = root;
           for (char ch : word.toCharArray()) {
                TrieNode child = current.subNode(ch);
                if (child.count == 1) {
                     current.childList.remove(child);
                     return;
                } else {
                     child.count--;
                     current = child;
                }
           }
           current.isEnd = false;
     }
}

public class TrieTest {
     public static void main(String[] args) {
           Scanner scan = new Scanner(System.in);
           /* Creating object of AATree */
           Trie t = new Trie();
           System.out.println("Trie Test\n");
           char ch;
           /* Perform tree operations */
           do {
                System.out.println("\nTrie Operations\n");
                System.out.println("1. insert ");
                System.out.println("2. delete");
                System.out.println("3. search");

                int choice = scan.nextInt();
                switch (choice) {
                case 1:
                     System.out.println("Enter string element to insert");
                     t.insert(scan.next());
                     break;
                case 2:
                     System.out.println("Enter string element to delete");
                     try {
                           t.remove(scan.next());
                     } catch (Exception e) {
                           System.out.println(e.getMessage() + " not found ");
                     }
                     break;
                case 3:
                     System.out.println("Enter string element to search");
                     System.out.println("Search result : " + t.search(scan.next()));
                     break;
                default:
                     System.out.println("Wrong Entry \n ");
                     break;
                }

                System.out.println("\nDo you want to continue (Type y or n) \n");
                ch = scan.next().charAt(0);
           } while (ch == 'Y' || ch == 'y');
     }
}//class TrieTest

o/p:-
Trie Test


Trie Operations

1. insert
2. delete
3. search
Patterns:-
NumberPattern.java
package Patterns;

import java.util.Scanner;

public class NumberPattern {
     public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);

        //Taking noOfRows value from the user

        System.out.println("How Many Rows You Want In Your Pyramid?");

        int noOfRows = sc.nextInt();

        //Initializing rowCount with 1

        int rowCount = 1;

        System.out.println("Here Is Your Pyramid");

        //Implementing the logic

        for (int i = noOfRows; i > 0; i--)
        {
            //Printing i spaces at the beginning of each row

            for (int j = 1; j <= i; j++)
            {
                System.out.print(" ");
            }

            //Printing 'rowCount' value 'rowCount' times at the end of each row

            for (int j = 1; j <= rowCount; j++)
            {
                System.out.print(rowCount+" ");
            }

            System.out.println();

            //Incrementing the rowCount

            rowCount++;
        }
    }
}

o/p:-
How Many Rows You Want In Your Pyramid?
2
Here Is Your Pyramid
  1
 2 2

Stars.java
package Patterns;

import java.util.Scanner;

public class Stars {
     public static void main(String[] args) {
           Scanner sc = new Scanner(System.in);

           // Taking noOfRows value from the user

           System.out.println("How Many Rows You Want In Your Pyramid?");

           int noOfRows = sc.nextInt();

           // Initializing rowCount with 1

           int rowCount = 1;

           System.out.println("Here Is Your Pyramid");

           // Implementing the logic

           for (int i = noOfRows; i > 0; i--) {
                // Printing i spaces at the beginning of each row

                for (int j = 1; j <= i; j++) {
                     System.out.print(" ");
                }

                // Printing * at the end of each row

                for (int j = 1; j <= rowCount; j++) {
                     System.out.print("* ");
                }

                System.out.println();

                // Incrementing the rowCount

                rowCount++;
           }
     }
}

o/p:-
How Many Rows You Want In Your Pyramid?
3
Here Is Your Pyramid
   *
  * *
 * * *

String Concatenation:-
StringExamples.java
package StringConcatenation;

//String, StringBuffer, StringBuilder classes performance in concatenation:-
public class StringExamples {
     public static void main(String[] args) {
           String s = "JAVA";

           long startTime = System.currentTimeMillis();

           for (int i = 0; i <= 10000; i++) {
                s = s + "J2EE";
           }

           long endTime = System.currentTimeMillis();

           System.out.println("Time taken by String class : "
                     + (endTime - startTime) + " ms");

           StringBuffer sb = new StringBuffer("JAVA");

           startTime = System.currentTimeMillis();

           for (int i = 0; i <= 10000; i++) {
                sb.append("J2EE");
           }

           endTime = System.currentTimeMillis();

           System.out.println("Time taken by StringBuffer class : "
                     + (endTime - startTime) + " ms");

           StringBuilder sb1 = new StringBuilder("JAVA");

           startTime = System.currentTimeMillis();

           for (int i = 0; i <= 10000; i++) {
                sb1.append("J2EE");
           }

           endTime = System.currentTimeMillis();

           System.out.println("Time taken by StringBuilder class : "
                     + (endTime - startTime) + " ms");
     }
}

o/p:-
Time taken by String class : 360 ms
Time taken by StringBuffer class : 0 ms
Time taken by StringBuilder class : 0 ms




Synchronization:-
SenderClass.java
package Synchronization;
//One more alternate implementation to demonstrate
//that synchronized can be used with only a part of
//method
public class SenderClass {
     public void send(String msg) {
           synchronized (this) {
                System.out.println("Sending\t" + msg);
                try {
                     Thread.sleep(1000);
                } catch (Exception e) {
                     System.out.println("Thread interrupted.");
                }
                System.out.println("\n" + msg + "Sent");
           }
     }
}

SyncDemo.java
/*
 * This synchronization is implemented in Java with a concept called monitors. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor.
 */
package Synchronization;

//A Java program to demonstrate working of synchronized.

//Sender Class used to send a message:
class Sender {
                public void send(String msg) {
                                System.out.println("Sending\t" + msg);
                                try {
                                                Thread.sleep(1000);
                                } catch (Exception e) {
                                                System.out.println("Thread  interrupted.");
                                }

                                System.out.println("\n" + msg + "Sent");
                }// send()
}

// Class for send a message using Threads
class ThreadedSend extends Thread {
                private String msg;
                private Thread t;
                Sender sender;

                // Recieves a message object and a string message to be sent
                ThreadedSend(String m, Sender obj) {
                                msg = m;
                                sender = obj;
                }

                public void run() {
                                // Only one thread can send a message at a time.
                                synchronized (sender) {
                                                // synchronizing the snd object
                                                sender.send(msg);
                                }// synchronized

                }// run()
}// ThreadedSend class

// Driver class Demo Program:
public class SyncDemo {
                public static void main(String args[]) {
                                Sender snd = new Sender();
                                ThreadedSend S1 = new ThreadedSend(" Hi ", snd);
                                ThreadedSend S2 = new ThreadedSend(" Bye ", snd);

                                // Start two threads of ThreadedSend type:
                                S1.start();
                                S2.start();

                                // wait for threads to end:
                                try {
                                                S1.join();
                                                S2.join();
                                } catch (Exception e) {
                                                System.out.println("Interrupted");
                                }
                }// main()
}// class SyncDemo main class
/*
 * The output is same every-time we run the program.
 *
 * In the above example, we chose to synchronize the Sender object inside the
 * run() method of the ThreadedSend class. Alternately, we could define the
 * whole send() block as synchronized and it would produce the same result. Then
 * we don’t have to synchronize the Message object inside the run() method in
 * ThreadedSend class.
 */

o/p:-
Sending    Hi

 Hi Sent
Sending    Bye

 Bye Sent

Strings:-
DuplicateCharsInString.java
package Strings;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class DuplicateCharsInString {
                public void findDuplicateChars(String str) {
                                Map<Character, Integer> dupMap = new HashMap<>();
                                char[] chrs = str.toCharArray();
                                for (Character ch : chrs) {
                                                if (dupMap.containsKey(ch)) {
                                                                dupMap.put(ch, dupMap.get(ch) + 1);
                                                } else {
                                                                dupMap.put(ch, 1);
                                                }
                                }// for
                                Set<Character> keys = dupMap.keySet();
                                for (Character ch : keys) {
                                                if (dupMap.get(ch) > 1) {
                                                                System.out.println(ch + "--->" + dupMap.get(ch));
                                                }
                                }// for
                }// findDuplicateChars()

                public static void main(String[] args) {
                                DuplicateCharsInString dcs=new DuplicateCharsInString();
                                dcs.findDuplicateChars("Java2Novice");
                }
}
o/p:-
v--->2
a--->2

ReverseEachWord.java BLC
package Strings;

public class ReverseEachWord {
     public static String reverseWord(String str) {
           String words[] = str.split("\\s");
           String reverseWord = "";
           for (String w : words) {
                StringBuilder sb = new StringBuilder(w);
                sb.reverse();
                reverseWord += sb.toString() + " ";
           }
           return reverseWord.trim();
     }
}

TestReverseEachWord.java
package Strings;

public class TestReverseEachWord {
     public static void main(String[] args) {
           System.out.println(ReverseEachWord.reverseWord("my name is raghu"));
     }
}

o/p:-
ym eman si uhgar

ReverseIteration.java
package Strings;

public class ReverseIteration {
     public static String reverseString(String str) {
           char ch[] = str.toCharArray();
           String rev = "";
           for (int i = ch.length - 1; i >= 0; i--) {
                rev += ch[i];
           }
           return rev;
     }
}

TestReverseIteration.java
package Strings;

public class TestReverseIteration {
     public static void main(String[] args) {
           System.out.println(ReverseIteration.reverseString("OLA CAB"));
     }
}

o/p:-
BAC ALO

StringFormatter.java
package Strings;

public class StringFormatter {
     public static String reverseString(String str) {
           StringBuilder sb = new StringBuilder(str);
           sb.reverse();
           return sb.toString();
     }

     public static String revString(String str1) {
           StringBuffer sb2 = new StringBuffer(str1);
           sb2.reverse();
           return sb2.toString();
     }
}

TestStringFormatter.java
package Strings;

public class TestStringFormatter {
     public static void main(String[] args) {
           System.out.println(StringFormatter.reverseString("my name is raghu"));
           System.out.println(StringFormatter.revString("Java"));
     }
}

o/p:-
uhgar si eman ym
avaJ

Algorithms:-
BinarySearch.java
package Algorithms;

public class BinarySearch {
     // Returns index of x if it is present in arr[l..
           // r], else return -1
           int binarySearch(int arr[], int l, int r, int x) {
                if (r >= l) {
                     int mid = l + (r - l) / 2;

                     // If the element is present at the
                     // middle itself
                     if (arr[mid] == x)
                           return mid;

                     // If element is smaller than mid, then
                     // it can only be present in left subarray
                     if (arr[mid] > x)
                           return binarySearch(arr, l, mid - 1, x);

                     // Else the element can only be present
                     // in right subarray
                     return binarySearch(arr, mid + 1, r, x);
                }

                // We reach here when element is not present
                // in array
                return -1;
           }

           // Driver method to test above
           public static void main(String args[]) {
                BinarySearch ob = new BinarySearch();
                int arr[] = { 2, 3, 4, 10, 40 };
                int n = arr.length;
                int x = 10;
                int result = ob.binarySearch(arr, 0, n - 1, x);
                if (result == -1)
                     System.out.println("Element not present");
                else
                     System.out.println("Element found at index " + result);
           }
}

o/p:-
Element found at index 3

BubbleSortExample.java
package Algorithms;

public class BubbleSortExample {
     static void bubbleSort(int[] arr) {
           int n = arr.length;
           int temp = 0;
           for (int i = 0; i < n; i++) {
                for (int j = 1; j < (n - i); j++) {
                     if (arr[j - 1] > arr[j]) {
                           // swap elements
                           temp = arr[j - 1];
                           arr[j - 1] = arr[j];
                           arr[j] = temp;
                     }

                }
           }

     }

     public static void main(String[] args) {
           int arr[] = { 3, 60, 35, 2, 45, 320, 5 };

           System.out.println("Array Before Bubble Sort");
           for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
           }
           System.out.println();

           bubbleSort(arr);// sorting array elements using bubble sort

           System.out.println("Array After Bubble Sort");
           for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
           }

     }
}

o/p:-
Array Before Bubble Sort
3 60 35 2 45 320 5
Array After Bubble Sort
2 3 5 35 45 60 320
FibonacciExample1.java
package Algorithms;

public class FibonacciExample1 {
     public static void main(String args[]) {
           int n1 = 0, n2 = 1, n3, i, count = 10;
           System.out.print(n1 + " " + n2);// printing 0 and 1

           for (i = 2; i < count; ++i)// loop starts from 2 because 0 and 1 are
                                                // already printed
           {
                n3 = n1 + n2;
                System.out.print(" " + n3);
                n1 = n2;
                n2 = n3;
           }

     }
}

o/p:-
0 1 1 2 3 5 8 13 21 34
FibonacciExample2.java
package Algorithms;

public class FibonacciExample2 {
     static int n1 = 0, n2 = 1, n3 = 0;

     static void printFibonacci(int count) {
           if (count > 0) {
                n3 = n1 + n2;
                n1 = n2;
                n2 = n3;
                System.out.print(" " + n3);
                printFibonacci(count - 1);
           }
     }

     public static void main(String args[]) {
           int count = 10;
           System.out.print(n1 + " " + n2);// printing 0 and 1
           printFibonacci(count - 2);// n-2 because 2 numbers are already printed
     }
}

o/p:-
0 1 1 2 3 5 8 13 21 34
QuickSort.java
package Algorithms;

//Java program for implementation of QuickSort
class QuickSort {
     /*
      * This function takes last element as pivot, places the pivot element at
      * its correct position in sorted array, and places all smaller (smaller
      * than pivot) to left of pivot and all greater elements to right of pivot
      */
     int partition(int arr[], int low, int high) {
           int pivot = arr[high];
           int i = (low - 1); // index of smaller element
           for (int j = low; j < high; j++) {
                // If current element is smaller than or
                // equal to pivot
                if (arr[j] <= pivot) {
                     i++;

                     // swap arr[i] and arr[j]
                     int temp = arr[i];
                     arr[i] = arr[j];
                     arr[j] = temp;
                }
           }

           // swap arr[i+1] and arr[high] (or pivot)
           int temp = arr[i + 1];
          arr[i + 1] = arr[high];
           arr[high] = temp;

           return i + 1;
     }

     /*
      * The main function that implements QuickSort() arr[] --> Array to be
      * sorted, low --> Starting index, high --> Ending index
      */
     void sort(int arr[], int low, int high) {
           if (low < high) {
                /*
                 * pi is partitioning index, arr[pi] is now at right place
                 */
                int pi = partition(arr, low, high);

                // Recursively sort elements before
                // partition and after partition
                sort(arr, low, pi - 1);
                sort(arr, pi + 1, high);
           }
     }

     /* A utility function to print array of size n */
     static void printArray(int arr[]) {
           int n = arr.length;
           for (int i = 0; i < n; ++i)
                System.out.print(arr[i] + " ");
           System.out.println();
     }

     // Driver program
     public static void main(String args[]) {
           int arr[] = { 10, 7, 8, 9, 1, 5 };
           int n = arr.length;

           QuickSort ob = new QuickSort();
           ob.sort(arr, 0, n - 1);

           System.out.println("sorted array");
           printArray(arr);
     }
}
o/p:-
sorted array
1 5 7 8 9 10


No comments:

Post a Comment

Prerequisites to install java on Windows OS:- Hold on 3 keys:--- Fn + Win + Home/Pause It shows the System Properties:- ...