diff --git a/Algorithm/BFS.java b/Algorithm/BFS.java new file mode 100644 index 0000000..1300ad9 --- /dev/null +++ b/Algorithm/BFS.java @@ -0,0 +1,72 @@ +import java.util.*; + + +class Main +{ + private int V; // No. of vertices + private LinkedList adj[]; //Adjacency Lists + + // Constructor + Graph(int v) + { + V = v; + adj = new LinkedList[v]; + for (int i=0; i queue = new LinkedList(); + + // Mark the current node as visited and enqueue it + visited[s]=true; + queue.add(s); + + while (queue.size() != 0) + { + // Dequeue a vertex from queue and print it + s = queue.poll(); + System.out.print(s+" "); + + Iterator i = adj[s].listIterator(); + while (i.hasNext()) + { + int n = i.next(); + if (!visited[n]) + { + visited[n] = true; + queue.add(n); + } + } + } + } + + public static void main(String args[]) + { + Graph g = new Graph(4); + + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + System.out.println("Following is Breadth First Traversal "+ + "(starting from vertex 2)"); + + g.BFS(2); + } +} + diff --git a/Algorithm/Binary_search.java b/Algorithm/Binary_search.java new file mode 100644 index 0000000..ec2d44b --- /dev/null +++ b/Algorithm/Binary_search.java @@ -0,0 +1,35 @@ +import java.util.*; +class Main{ + public static void main(String args[]){ + int numArray[] = {5,10,15,20,25,30,35}; + System.out.println("The input array: " + Arrays.toString(numArray)); + //key to be searched + int key = 20; + System.out.println("\nKey to be searched=" + key); + //set first to first index + int first = 0; + //set last to last elements in array + int last=numArray.length-1; + //calculate mid of the array + int mid = (first + last)/2; + //while first and last do not overlap + while( first <= last ){ + //if the mid < key, then key to be searched is in the first half of array + if ( numArray[mid] < key ){ + first = mid + 1; + }else if ( numArray[mid] == key ){ + //if key = element at mid, then print the location + System.out.println("Element is found at index: " + mid); + break; + }else{ + //the key is to be searched in the second half of the array + last = mid - 1; + } + mid = (first + last)/2; + } + //if first and last overlap, then key is not present in the array + if ( first > last ){ + System.out.println("Element is not found!"); + } + } +} diff --git a/Algorithm/dfs.java b/Algorithm/dfs.java new file mode 100644 index 0000000..ac63090 --- /dev/null +++ b/Algorithm/dfs.java @@ -0,0 +1,90 @@ +import java.util.*; + +public class Main +{ + + static class Graph + { + int V; //Number of Vertices + + LinkedList[] adj; // adjacency lists + + //Constructor + Graph(int V) + { + this.V = V; + adj = new LinkedList[V]; + + for (int i = 0; i < adj.length; i++) + adj[i] = new LinkedList(); + + } + + //To add an edge to graph + void addEdge(int v, int w) + { + adj[v].add(w); // Add w to v’s list. + } + + // prints all not yet visited vertices reachable from s + void DFS(int s) + { + // Initially mark all vertices as not visited + Vector visited = new Vector(V); + for (int i = 0; i < V; i++) + visited.add(false); + + // Create a stack for DFS + Stack stack = new Stack<>(); + + // Push the current source node + stack.push(s); + + while(stack.empty() == false) + { + // Pop a vertex from stack and print it + s = stack.peek(); + stack.pop(); + + // Stack may contain same vertex twice. So + // we need to print the popped item only + // if it is not visited. + if(visited.get(s) == false) + { + System.out.print(s + " "); + visited.set(s, true); + } + + // Get all adjacent vertices of the popped vertex s + // If a adjacent has not been visited, then push it + // to the stack. + Iterator itr = adj[s].iterator(); + + while (itr.hasNext()) + { + int v = itr.next(); + if(!visited.get(v)) + stack.push(v); + } + + } + } + } + + + public static void main(String[] args) + { + // Total 5 vertices in graph + Graph g = new Graph(5); + + g.addEdge(1, 0); + g.addEdge(0, 2); + g.addEdge(2, 1); + g.addEdge(0, 3); + g.addEdge(1, 4); + + System.out.println("Following is the Depth First Traversal"); + g.DFS(0); + } +} + diff --git a/Algorithm/shortest_path.java b/Algorithm/shortest_path.java new file mode 100644 index 0000000..6a6a269 --- /dev/null +++ b/Algorithm/shortest_path.java @@ -0,0 +1,97 @@ +// A Java program for Dijkstra's single source shortest path algorithm. +// The program is for adjacency matrix representation of the graph +import java.util.*; +import java.lang.*; +import java.io.*; + +class ShortestPath { + // A utility function to find the vertex with minimum distance value, + // from the set of vertices not yet included in shortest path tree + static final int V = 9; + int minDistance(int dist[], Boolean sptSet[]) + { + // Initialize min value + int min = Integer.MAX_VALUE, min_index = -1; + + for (int v = 0; v < V; v++) + if (sptSet[v] == false && dist[v] <= min) { + min = dist[v]; + min_index = v; + } + + return min_index; + } + + // A utility function to print the constructed distance array + void printSolution(int dist[], int n) + { + System.out.println("Vertex Distance from Source"); + for (int i = 0; i < V; i++) + System.out.println(i + " tt " + dist[i]); + } + + // Function that implements Dijkstra's single source shortest path + // algorithm for a graph represented using adjacency matrix + // representation + void dijkstra(int graph[][], int src) + { + int dist[] = new int[V]; // The output array. dist[i] will hold + // the shortest distance from src to i + + // sptSet[i] will true if vertex i is included in shortest + // path tree or shortest distance from src to i is finalized + Boolean sptSet[] = new Boolean[V]; + + // Initialize all distances as INFINITE and stpSet[] as false + for (int i = 0; i < V; i++) { + dist[i] = Integer.MAX_VALUE; + sptSet[i] = false; + } + + // Distance of source vertex from itself is always 0 + dist[src] = 0; + + // Find shortest path for all vertices + for (int count = 0; count < V - 1; count++) { + // Pick the minimum distance vertex from the set of vertices + // not yet processed. u is always equal to src in first + // iteration. + int u = minDistance(dist, sptSet); + + // Mark the picked vertex as processed + sptSet[u] = true; + + // Update dist value of the adjacent vertices of the + // picked vertex. + for (int v = 0; v < V; v++) + + // Update dist[v] only if is not in sptSet, there is an + // edge from u to v, and total weight of path from src to + // v through u is smaller than current value of dist[v] + if (!sptSet[v] && graph[u][v] != 0 && + dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) + dist[v] = dist[u] + graph[u][v]; + } + + // print the constructed distance array + printSolution(dist, V); + } + + // Driver method + public static void main(String[] args) + { + /* Let us create the example graph discussed above */ + int graph[][] = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, + { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, + { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, + { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, + { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, + { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, + { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, + { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, + { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; + ShortestPath t = new ShortestPath(); + t.dijkstra(graph, 0); + } +} +// This code is contributed by Aakash Hasija diff --git a/AnagramCheck.java b/AnagramCheck.java new file mode 100644 index 0000000..18a1fa4 --- /dev/null +++ b/AnagramCheck.java @@ -0,0 +1,67 @@ +import java.util.Arrays; + +/** + * Java program - String Anagram Example. + * This program checks if two Strings are anagrams or not + * + * @author Javin Paul + */ +public class AnagramCheck { + + /* + * One way to find if two Strings are anagram in Java. This method + * assumes both arguments are not null and in lowercase. + * + * @return true, if both String are anagram + */ + public static boolean isAnagram(String word, String anagram){ + if(word.length() != anagram.length()){ + return false; + } + + char[] chars = word.toCharArray(); + + for(char c : chars){ + int index = anagram.indexOf(c); + if(index != -1){ + anagram = anagram.substring(0,index) + + anagram.substring(index +1, anagram.length()); + }else{ + return false; + } + } + + return anagram.isEmpty(); + } + + /* + * Another way to check if two Strings are anagram or not in Java + * This method assumes that both word and anagram are not null and lowercase + * @return true, if both Strings are anagram. + */ + public static boolean iAnagram(String word, String anagram){ + char[] charFromWord = word.toCharArray(); + char[] charFromAnagram = anagram.toCharArray(); + Arrays.sort(charFromWord); + Arrays.sort(charFromAnagram); + + return Arrays.equals(charFromWord, charFromAnagram); + } + + + public static boolean checkAnagram(String first, String second){ + char[] characters = first.toCharArray(); + StringBuilder sbSecond = new StringBuilder(second); + + for(char ch : characters){ + int index = sbSecond.indexOf("" + ch); + if(index != -1){ + sbSecond.deleteCharAt(index); + }else{ + return false; + } + } + + return sbSecond.length()==0 ? true : false; + } +} diff --git a/AvoidDeadLock.java b/AvoidDeadLock.java new file mode 100644 index 0000000..d94c0b5 --- /dev/null +++ b/AvoidDeadLock.java @@ -0,0 +1,70 @@ + public class AvoidDeadlock + { + public static void main(String[] args) throws InterruptedException + { + //creating object of the Object class + Object object1 = new Object(); + Object object2 = new Object(); + Object object3 = new Object(); + //creating constructor of the Thread class and passing SynchroniseThread object as a parameter + Thread thread1 = new Thread(new SynchroniseThread(object1, object2), "thread1"); + Thread thread2 = new Thread(new SynchroniseThread(object2, object3), "thread2"); + //executing thread1 + thread1.start(); + //the sleep() method suspends the execution of the current thread (thread1) for the specific period + Thread.sleep(2000); + //executing thread2 + thread2.start(); + //suspends the execution of the current thread (thread2) for the specific period + Thread.sleep(2000); + } + } + class SynchroniseThread implements Runnable + { + private Object object1; + private Object object2; + public SynchroniseThread(Object o1, Object o2) + { + this.object1=o1; + this.object2=o2; + } + //overriding run() method of the Thread class + @Override + //it allows two threads are running concurrently + public void run() + { + //getteing the current thread name + String name = Thread.currentThread().getName(); + System.out.println(name + " acquire lock on " + object1); + //Synchronized() method is used to lock an object for any shared resource. When a thread invokes the synchronized() method, + //it automatically acquires the lock for that object and releases it when the thread completes its task. + synchronized (object1) + { + System.out.println(name + " acquired lock on " + object1); + //calling work() method + work(); + } + System.out.println(name + " released lock of " + object1); + System.out.println(name + " acquire lock on " + object2); + synchronized (object2) + { + System.out.println(name + " acquire lock on " + object2); + work(); + } + System.out.println(name + " released lock of " + object2); + System.out.println(name + " execution is completed."); + } + private void work() + { + try + { + //the sleep() method suspends the execution of the current thread for 5 seconds + Thread.sleep(5000); + } + catch (InterruptedException e) + { + e.printStackTrace(); + } + } + } + diff --git a/BucketSort.java b/BucketSort.java new file mode 100644 index 0000000..9651e33 --- /dev/null +++ b/BucketSort.java @@ -0,0 +1,47 @@ +// Bucket sort in Java + +import java.util.ArrayList; +import java.util.Collections; + +public class BucketSort { + public void bucketSort(float[] arr, int n) { + if (n <= 0) + return; + @SuppressWarnings("unchecked") + ArrayList[] bucket = new ArrayList[n]; + + // Create empty buckets + for (int i = 0; i < n; i++) + bucket[i] = new ArrayList(); + + // Add elements into the buckets + for (int i = 0; i < n; i++) { + int bucketIndex = (int) arr[i] * n; + bucket[bucketIndex].add(arr[i]); + } + + // Sort the elements of each bucket + for (int i = 0; i < n; i++) { + Collections.sort((bucket[i])); + } + + // Get the sorted array + int index = 0; + for (int i = 0; i < n; i++) { + for (int j = 0, size = bucket[i].size(); j < size; j++) { + arr[index++] = bucket[i].get(j); + } + } + } + + // Driver code + public static void main(String[] args) { + BucketSort b = new BucketSort(); + float[] arr = { (float) 0.42, (float) 0.32, (float) 0.33, (float) 0.52, (float) 0.37, (float) 0.47, + (float) 0.51 }; + b.bucketSort(arr, 7); + + for (float i : arr) + System.out.print(i + " "); + } +} diff --git a/Dog.java b/Dog.java new file mode 100644 index 0000000..bd2d927 --- /dev/null +++ b/Dog.java @@ -0,0 +1,60 @@ +/ Java program to illustrate the concept +// of classes and objects + +// Class Declaration + +public class Dog { + // Instance Variables + String name; + String breed; + int age; + String color; + + // Constructor Declaration of Class + public Dog(String name, String breed, + int age, String color) + { + this.name = name; + this.breed = breed; + this.age = age; + this.color = color; + } + + // method 1 + public String getName() + { + return name; + } + + // method 2 + public String getBreed() + { + return breed; + } + + // method 3 + public int getAge() + { + return age; + } + + // method 4 + public String getColor() + { + return color; + } + + @Override + public String toString() + { + return ("Hi my name is " + this.getName() + + ".\nMy breed, age and color are " + this.getBreed() + + ", " + this.getAge() + ", " + this.getColor()); + } + + public static void main(String[] args) + { + Dog tuffy = new Dog("tuffy", "papillon", 5, "white"); + System.out.println(tuffy.toString()); + } +} \ No newline at end of file diff --git a/Heapdemo.java b/Heapdemo.java new file mode 100644 index 0000000..b51ff8a --- /dev/null +++ b/Heapdemo.java @@ -0,0 +1,96 @@ +import java.util.*; + + +class Heap{ + + int heapSize; + + void build_max_heap(int[] a) + { + heapSize=a.length; + for(int i=(heapSize/2);i>=0;i--) + max_heapify(a,i); + + } + + void max_heapify(int[] a,int i) + { + int l=2*i+1; + int r=2*i+2; + int largest=i; + if(la[largest]) + largest=l; + if(ra[largest]) + largest=r; + if(largest!=i) + { + int t=a[i]; + a[i]=a[largest]; + a[largest]=t; + max_heapify(a,largest); + } + + } + + //to delete the max element + + int extract_max(int[] a) + { + if(heapSize<0) + System.out.println("underflow"); + int max=a[0]; + a[0]=a[heapSize-1]; + heapSize--; + max_heapify(a,0); + return max; + } + + void increase_key(int[] a,int i,int key) + { + if(key=0 && a[(i-1)/2] 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 x + y; + + // lambda expression multiplication for two parameters + // This expression also implements 'FuncInter1' interface + FuncInter1 multiply = (int x, int y) -> x * y; + + // Creating an object of Test to call operate using + // different implementations using lambda Expressions + Test tobj = new Test(); + + // Add two numbers using lambda expression + System.out.println("Addition is " + + tobj.operate(6, 3, add)); + + // Multiply two numbers using lambda expression + System.out.println("Multiplication is " + + tobj.operate(6, 3, multiply)); + + // lambda expression for single parameter + // This expression implements 'FuncInter2' interface + FuncInter2 fobj = message ->System.out.println("Hello " + + message); + fobj.sayMessage("hello"); + } +} \ No newline at end of file diff --git a/Readme.md b/Readme.md deleted file mode 100644 index e69de29..0000000 diff --git a/Subarray.java b/Subarray.java new file mode 100644 index 0000000..4e696e8 --- /dev/null +++ b/Subarray.java @@ -0,0 +1,58 @@ +public class Subarray { + public static void main(String[] args) { + int[] arr = { 10, 20, -30, 40 }; + logic2(arr); + + } + + public static void logic1(int[] arr) { + int ans = Integer.MIN_VALUE; + for (int s = 0; s < arr.length; s++) { + for (int e = s; e < arr.length; e++) { +// System.out.println(s + " " + e); + int sum = 0; + for (int idx = s; idx <= e; idx++) { + System.out.print(arr[idx] + " "); + sum = sum + arr[idx]; + } + System.out.println("=>" + sum); + if (sum > ans) { + ans = sum; + } + } + } + System.out.println(ans); + } + + public static void logic2(int[] arr) { + int ans = Integer.MIN_VALUE; + for (int s = 0; s < arr.length; s++) { + int sum = 0; + for (int e = s; e < arr.length; e++) { +// System.out.println(s + " " + e); + sum = sum + arr[e]; + System.out.println(sum); + if (sum > ans) { + ans = sum; + } + } + } + System.out.println("==" + ans); + System.out.println(ans); + } + + public static void logic3(int[] arr) { + int sum = 0; + int max = 0; + for (int i = 0; i < arr.length; i++) { + sum = sum + arr[i]; + if (sum < 0) { + sum = 0; + } + if (max < sum) { + max = sum; + } + } + } + +} diff --git a/Test.java b/Test.java new file mode 100644 index 0000000..3c18a11 --- /dev/null +++ b/Test.java @@ -0,0 +1,29 @@ +// Java program to demonstrate how +// to use gcd method of BigInteger class + +import java.math.BigInteger; + +class Test { + public static int gcd(int a, int b) + { + BigInteger b1 = BigInteger.valueOf(a); + BigInteger b2 = BigInteger.valueOf(b); + BigInteger gcd = b1.gcd(b2); + return gcd.intValue(); + } + + public static long gcd(long a, long b) + { + BigInteger b1 = BigInteger.valueOf(a); + BigInteger b2 = BigInteger.valueOf(b); + BigInteger gcd = b1.gcd(b2); + return gcd.longValue(); + } + + // Driver method + public static void main(String[] args) + { + System.out.println(gcd(3, 5)); + System.out.println(gcd(10000000000L, 600000000L)); + } +} diff --git a/TestMethod.java b/TestMethod.java new file mode 100644 index 0000000..d8d6390 --- /dev/null +++ b/TestMethod.java @@ -0,0 +1,30 @@ +class Student{ + int rollno; + String name; + static String college = "ITS"; + //static method to change the value of static variable + static void change(){ + college = "BBDIT"; + } + //constructor to initialize the variable + Student(int r, String n){ + rollno = r; + name = n; + } + //method to display values + void display(){System.out.println(rollno+" "+name+" "+college);} +} +//Test class to create and display the values of object +public class TestMethod{ + public static void main(String args[]){ + Student.change();//calling change method + //creating objects + Student s1 = new Student(111,"Karan"); + Student s2 = new Student(222,"Aryan"); + Student s3 = new Student(333,"Sonoo"); + //calling display method + s1.display(); + s2.display(); + s3.display(); + } +} \ No newline at end of file diff --git a/TicTacToe.java b/TicTacToe.java new file mode 100644 index 0000000..8b2cc0c --- /dev/null +++ b/TicTacToe.java @@ -0,0 +1,174 @@ +// A simple program to demonstrate +// Tic-Tac-Toe Game. +import java.util.*; + +public class GFG { + + static String[] board; + static String turn; + + + // CheckWinner method will + // decide the combination + // of three box given below. + static String checkWinner() + { + for (int a = 0; a < 8; a++) { + String line = null; + + switch (a) { + case 0: + line = board[0] + board[1] + board[2]; + break; + case 1: + line = board[3] + board[4] + board[5]; + break; + case 2: + line = board[6] + board[7] + board[8]; + break; + case 3: + line = board[0] + board[3] + board[6]; + break; + case 4: + line = board[1] + board[4] + board[7]; + break; + case 5: + line = board[2] + board[5] + board[8]; + break; + case 6: + line = board[0] + board[4] + board[8]; + break; + case 7: + line = board[2] + board[4] + board[6]; + break; + } + //For X winner + if (line.equals("XXX")) { + return "X"; + } + + // For O winner + else if (line.equals("OOO")) { + return "O"; + } + } + + for (int a = 0; a < 9; a++) { + if (Arrays.asList(board).contains( + String.valueOf(a + 1))) { + break; + } + else if (a == 8) { + return "draw"; + } + } + + // To enter the X Or O at the exact place on board. + System.out.println( + turn + "'s turn; enter a slot number to place " + + turn + " in:"); + return null; + } + + // To print out the board. + /* |---|---|---| + | 1 | 2 | 3 | + |-----------| + | 4 | 5 | 6 | + |-----------| + | 7 | 8 | 9 | + |---|---|---|*/ + + static void printBoard() + { + System.out.println("|---|---|---|"); + System.out.println("| " + board[0] + " | " + + board[1] + " | " + board[2] + + " |"); + System.out.println("|-----------|"); + System.out.println("| " + board[3] + " | " + + board[4] + " | " + board[5] + + " |"); + System.out.println("|-----------|"); + System.out.println("| " + board[6] + " | " + + board[7] + " | " + board[8] + + " |"); + System.out.println("|---|---|---|"); + } + + public static void main(String[] args) + { + Scanner in = new Scanner(System.in); + board = new String[9]; + turn = "X"; + String winner = null; + + for (int a = 0; a < 9; a++) { + board[a] = String.valueOf(a + 1); + } + + System.out.println("Welcome to 3x3 Tic Tac Toe."); + printBoard(); + + System.out.println( + "X will play first. Enter a slot number to place X in:"); + + while (winner == null) { + int numInput; + + // Exception handling. + // numInput will take input from user like from 1 to 9. + // If it is not in range from 1 to 9. + // then it will show you an error "Invalid input." + try { + numInput = in.nextInt(); + if (!(numInput > 0 && numInput <= 9)) { + System.out.println( + "Invalid input; re-enter slot number:"); + continue; + } + } + catch (InputMismatchException e) { + System.out.println( + "Invalid input; re-enter slot number:"); + continue; + } + + // This game has two player x and O. + // Here is the logic to decide the turn. + if (board[numInput - 1].equals( + String.valueOf(numInput))) { + board[numInput - 1] = turn; + + if (turn.equals("X")) { + turn = "O"; + } + else { + turn = "X"; + } + + printBoard(); + winner = checkWinner(); + } + else { + System.out.println( + "Slot already taken; re-enter slot number:"); + } + } + + // If no one win or lose from both player x and O. + // then here is the logic to print "draw". + if (winner.equalsIgnoreCase("draw")) { + System.out.println( + "It's a draw! Thanks for playing."); + } + + // For winner -to display Congratulations! message. + else { + System.out.println( + "Congratulations! " + winner + + "'s have won! Thanks for playing."); + } + } +} + diff --git a/reverse.java b/reverse.java new file mode 100644 index 0000000..9598d0e --- /dev/null +++ b/reverse.java @@ -0,0 +1,14 @@ +public class ReverseNumberExample1 +{ +public static void main(String[] args) +{ +int number = 987654, reverse = 0; +while(number != 0) +{ +int remainder = number % 10; +reverse = reverse * 10 + remainder; +number = number/10; +} +System.out.println("The reverse of the given number is: " + reverse); +} +} diff --git a/sortAsc.java b/sortAsc.java new file mode 100644 index 0000000..55d89f3 --- /dev/null +++ b/sortAsc.java @@ -0,0 +1,33 @@ + public class sortAsc { + public static void main(String[] args) { + + //Initialize array + int [] arr = new int [] {5, 2, 8, 7, 1}; + int temp = 0; + + //Displaying elements of original array + System.out.println("Elements of original array: "); + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + " "); + } + + //Sort the array in ascending order + for (int i = 0; i < arr.length; i++) { + for (int j = i+1; j < arr.length; j++) { + if(arr[i] > arr[j]) { + temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + } + + System.out.println(); + + //Displaying elements of array after sorting + System.out.println("Elements of array sorted in ascending order: "); + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + " "); + } + } + } diff --git a/stooge_sort.java b/stooge_sort.java new file mode 100644 index 0000000..00ef951 --- /dev/null +++ b/stooge_sort.java @@ -0,0 +1,41 @@ +public class stooge_sort { + static void stoogesort(int arr[], int l, int h) { + if (l >= h) + return; + + // If first element is smaller + // than last, swap them + if (arr[l] > arr[h]) { + int t = arr[l]; + arr[l] = arr[h]; + arr[h] = t; + } + + // If there are more than 2 elements in + // the array + if (h - l + 1 > 2) { + int t = (h - l + 1) / 3; + + // Recursively sort first 2/3 elements + stoogesort(arr, l, h - t); + + // Recursively sort last 2/3 elements + stoogesort(arr, l + t, h); + + // Recursively sort first 2/3 elements + // again to confirm + stoogesort(arr, l, h - t); + } + } + + // Driver Code + public static void main(String args[]) { + int arr[] = { 2, 4, 5, 3, 1 }; + int n = arr.length; + + stoogesort(arr, 0, n - 1); + + for (int i = 0; i < n; i++) + System.out.print(arr[i] + " "); + } +}