fix: files naming and remove unncessary index

pull/225/head^2
Ming Tsai 2021-04-17 21:45:05 -04:00
parent 76bbb1a443
commit 8ca052d2c7
43 changed files with 6 additions and 1823 deletions

View File

@ -1,17 +1,17 @@
# Python
## Arrays
1. [Count Inversions](arrays/count-inversions.java)
2. [Kadanes Algorithm](arrays/Kadanes_Algorithm.java)
3. [Left Rotation](arrays/left_rotation.java)
1. [Counting Inversions](arrays/counting-inversions.java)
2. [Kadanes Algorithm](arrays/kadanes-algorithm.java)
3. [Left Rotation](arrays/left-rotation.java)
4. [Unique Digits of Large Number](arrays/unique-digits-of-large-number.java)
## Graphs
1. [Dijkstras](graphs/Dijkstras.java)
1. [Dijkstras](graphs/dijkstras.java)
## Linked Lists
1. [Circular](linked-lists/circular.java)
2. [Clone Linked List](linked-lists/clone-linkedlist-with-rnd-pointer.java)
2. [Clone Linked List](linked-lists/clone-linkedlist.java)
3. [Doubly](linked-lists/doubly.java)
4. [Reverse](linked-lists/reverse.java)
5. [Singly](linked-lists/singly.java)
@ -52,4 +52,4 @@
6. [Tokenizer](strings/tokenizer.java)
## Trees
1. [Pre in Post Traversal](trees/pre_in_post_traversal.java)
1. [Pre in Post Traversal](trees/pre-in-post-traversal.java)

View File

@ -16,10 +16,3 @@
10. [Variable declaration](c-or-cpp/variable-declaration.cpp)
11. [Data before and after sorting](c-or-cpp/data-before-sort.cpp)
12. [Even and odd no. ](c-or-cpp/even-and-odd.c)
### Java
1. [Counting Inversions](java/count-inversions.java)
2. [Kadane's Algorithm](java/Kadanes_Algorithm.java)
2. [Left Rotation of Array](java/left_rotation.java)
3. [Finding unique digits of large number](java/unique-digits-of-large-number.java)

View File

@ -1,30 +0,0 @@
// Java program to print largest contiguous array sum
import java.io.*;
import java.util.*;
class Kadane
{
public static void main (String[] args)
{
int [] a = {-2, -3, 4, -1, -2, 1, 5, -3};
System.out.println("Maximum contiguous sum is " +
maxSubArraySum(a));
}
static int maxSubArraySum(int a[])
{
int size = a.length;
int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
}

View File

@ -1,59 +0,0 @@
// Algorithm Type: Divide & Conquer
// Time Complexity: O(n*log(n))
import java.io.File;
import java.lang.reflect.Array;
import java.util.*;
public class inversions {
private static long count_split_inv(int[] arr, int[] left, int[] right) {
long split_inv = 0;
int ridx = 0, lidx = 0;
int size = arr.length;
int rsize = right.length;
int lsize = left.length;
for (int i = 0; i < size; i++) {
if (lidx != lsize && ridx != rsize) {
if (right[ridx] <= left[lidx]) {
arr[i] = right[ridx];
ridx++;
split_inv += lsize - lidx;
} else {
arr[i] = left[lidx];
lidx++;
}
} else if (lidx == lsize) {
arr[i] = right[ridx];
ridx++;
} else if (ridx == rsize) {
arr[i] = left[lidx];
lidx++;
}
}
return split_inv;
}
private static long count_inversions(int[] arr) {
int size = arr.length;
if (size == 1) {
return 0;
}
int[] left = Arrays.copyOfRange(arr, 0, size / 2);
int[] right = Arrays.copyOfRange(arr, size / 2, size);
long left_inv = count_inversions(left);
long right_inv = count_inversions(right);
long split_inv = count_split_inv(arr, left, right);
return left_inv + right_inv + split_inv;
}
public static void main(String[] args) {
try {
int[] arr = {8, 2, 1, 5, 7, 3, 9, 2, 0, 1};
System.out.println(count_inversions(arr));
} catch (Exception e) {
System.out.println("Err... ");
}
}
}

View File

@ -1,51 +0,0 @@
public class left_rotation{
public static void rotateToLeft(int [] arr){
if(arr == null || arr.length == 0){
System.out.println("no rotation possible");
return;
}
//take the first element
int firstElement = arr[0];
//move everything in the left
for(int i = 0; i < arr.length -1; i++){
arr[i] = arr[i + 1];
}
//the first element become the last element
arr[arr.length - 1] = firstElement;
}
public static void print(int [] arr){
System.out.print("[");
for(int i = 0; i < arr.length; i++)
System.out.print(arr[i] + ", ");
System.out.println("]");
}
public static void main(String [] args){
int [] arr = {1,2,3,4,5,6,7,8,9};
int n = 3; //number of times to rotate the array
System.out.print("before: ");
print(arr);
System.out.println("rotating " + n + " times to left");
for(int i = 0; i < n; i++)
rotateToLeft(arr); //move to left n times
System.out.print("after: ");
print(arr);
}
}
/*
to run the file:
javac left_rotation.java
java left_rotation
result:
before: [1, 2, 3, 4, 5, 6, 7, 8, 9, ]
rotating 3 times to left
after: [4, 5, 6, 7, 8, 9, 1, 2, 3, ]
*/

View File

@ -1,62 +0,0 @@
import java.util.*;
public class UniqueDigitsOfLargeNumber {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int l,i,j,l1=0;
String s,p="";
char c,d;
System.out.println("Enter a large number");
s=sc.nextLine();
l=s.length();
for(i=0;i<l;i++)
{
c=s.charAt(i);
for(j=0;j<l1;j++)
{
if(p.charAt(j)==c)
break;
}
if(j==l1)
{
p=p+c;
l1=p.length();
}
}
System.out.print("The unique digits present in "+Long.parseLong(s)+" are ");
if(l1>1)
{
for(i=0;i<l1-1;i++)
{
System.out.print(p.charAt(i)+", ");
}
System.out.println("and "+p.charAt(l1-1)+".");
c=p.charAt(0);
for(i=0;i<l1;i++)
{
if(p.charAt(i)>c)
c=p.charAt(i);
}
s="";
s=s+c;
c--;
for(d=c;d>='0';d--)
{
for(i=0;i<l1;i++)
{
if(p.charAt(i)==d)
s=s+d;
}
}
System.out.println("The largest number possible out of these unique digits is "+Long.parseLong(s));
}
else
{
System.out.println(p.charAt(0)+".");
System.out.println("The largest number possible out of these unique digits is "+Integer.parseInt(p));
}
}
}

View File

@ -6,6 +6,3 @@
2. [Bellman Ford Algorithm](c-or-cpp/bellman-ford.cpp)
3. [Prim's Algorithm](c-or-cpp/Prim's-algorithm.c)
### Java
1. [Dijkstras Algorithm](java/Dijkstras.java)

View File

@ -1,133 +0,0 @@
import java.util.*;
class AdjListNode
{
int dest;
int weight;
AdjListNode(int dest,int weight)
{
this.dest=dest;
this.weight=weight;
}
}
class NodeComparator implements Comparator<AdjListNode>
{
@Override
public int compare(AdjListNode node1, AdjListNode node2)
{
if (node1.weight < node2.weight)
return -1;
if (node1.weight > node2.weight)
return 1;
return 0;
}
}
class Dijkstras
{
public int[] dijkstras(List<List<AdjListNode>> adj_list,int source)
{
int[] distance = new int[adj_list.size()];
Set<Integer> completed = new HashSet<Integer>();
for(int i=0;i<distance.length;++i)
{
distance[i] = Integer.MAX_VALUE;
}
PriorityQueue<AdjListNode> pq = new PriorityQueue<>(adj_list.size(),new NodeComparator());
AdjListNode source_node = new AdjListNode(source,0);
for(int i=0;i<distance.length;++i)
{
pq.add(new AdjListNode(i,Integer.MAX_VALUE));
}
pq.add(source_node);
distance[source]=0;
while(!pq.isEmpty())
{
AdjListNode current = pq.remove();
if(!completed.contains(current.dest))
{
completed.add(current.dest);
for(AdjListNode n :adj_list.get(current.dest) )
{
if( distance[n.dest] > (distance[current.dest]+n.weight))
{
distance[n.dest] = distance[current.dest]+n.weight;
pq.add(new AdjListNode(n.dest, distance[n.dest]));
}
}
}
}
return distance;
}
public static void main(String args[])
{
/*
SAMPLE INPUT AND OUTPUT
___________________________
Input:
__________
Please enter the number of nodes N. Vertices will be [0,N-1]
6
Please Enter the number of Edges
9
Please enter each edge in the sequence <starting node> <destination node> <weight>
0 1 1
0 2 5
1 2 2
1 4 1
1 3 2
2 4 2
3 5 1
3 4 3
4 5 2
Please enter source vertex
0
Output:
___________
Distances from source 0
Node0--->0
Node1--->1
Node2--->3
Node3--->3
Node4--->2
Node5--->4
*/
List<List<AdjListNode>> adj_list = new ArrayList<List<AdjListNode>>();
System.out.println("Please enter the number of nodes N. Vertices will be [0,N-1]");
Scanner sc = new Scanner(System.in);
int v = sc.nextInt();
for(int i=0;i<v;++i)
adj_list.add(new ArrayList<AdjListNode>());
System.out.println("Please enter the number of edges");
int e = sc.nextInt();
System.out.println("Please enter each edge in the sequence <starting node> <destination node> <weight>");
// Sample Data: 0 2 5 (edge from 0 to 2 with weight 5)
for(int i=0;i<e;++i)
{
int startnode = sc.nextInt();
int destnode = sc.nextInt();
int weight = sc.nextInt();
adj_list.get(startnode).add(new AdjListNode(destnode,weight));
}
int source;
System.out.println("Please enter source vertex");
source = sc.nextInt();
Dijkstras d = new Dijkstras();
int[] distances = d.dijkstras(adj_list, source); //source vertex is taken as 0
System.out.println("Distances from source "+source);
for(int i=0;i<distances.length;++i)
{
if(distances[i]==Integer.MAX_VALUE)
System.out.println("Node"+i+"--->"+"infinity");
else
System.out.println("Node"+i+"--->"+distances[i]);
}
}
}

View File

@ -9,11 +9,3 @@
5. [Insertion Linked List](c-or-cpp/all-possible-insertion.cpp)
6. [Josephus Problem Using Circular Linked List](c-or-cpp/josephus-problem.c)
7. [Merge Two Singly linked List](c-or-cpp/merge.cpp)
### Java
1. [Singly Linked List](java/singly.java)
2. [Doubly Linked List](java/doubly.java)
3. [Circular Linked List](java/circular.java)
4. [Reverse Linked List](java/reverse.java)
5. [Clone Linked List with Random Pointer](java/clone-linkedlist-with-rnd-pointer.java)

View File

@ -5,8 +5,3 @@
1. [Queue using linked list](c-or-cpp/queue-linked-list.cpp)
2. [Circular Queue using linked list](c-or-cpp/circular-queue-linked-list.cpp)
3. [Double Ended Queue (using arrays)](c-or-cpp/double-ended-queue-using-array.c)
### Java
1. [Queue using linked list](java/queue-linked-list.java)
2. [Circular Queue using linked list](java/circular-queue-linked-list.java)

View File

@ -1,96 +0,0 @@
// Java program for insertion and
// deletion in Circular Queue
import java.util.*;
class Solution {
// Structure of a Node
static class Node {
int data;
Node link;
}
static class Queue {
Node front, rear;
}
// Function to create Circular queue
static void enQueue(Queue q, int value)
{
Node temp = new Node();
temp.data = value;
if (q.front == null)
q.front = temp;
else
q.rear.link = temp;
q.rear = temp;
q.rear.link = q.front;
}
// Function to delete element from Circular Queue
static int deQueue(Queue q)
{
if (q.front == null) {
System.out.printf("Queue is empty");
return Integer.MIN_VALUE;
}
// If this is the last node to be deleted
int value; // Value to be dequeued
if (q.front == q.rear) {
value = q.front.data;
q.front = null;
q.rear = null;
}
else // There are more than one nodes
{
Node temp = q.front;
value = temp.data;
q.front = q.front.link;
q.rear.link = q.front;
}
return value;
}
// Function displaying the elements of Circular Queue
static void displayQueue(Queue q)
{
Node temp = q.front;
System.out.printf("\nElements in Circular Queue are: ");
while (temp.link != q.front) {
System.out.printf("%d ", temp.data);
temp = temp.link;
}
System.out.printf("%d", temp.data);
}
/* Driver of the program */
public static void main(String args[])
{
// Create a queue and initialize front and rear
Queue q = new Queue();
q.front = q.rear = null;
// Inserting elements in Circular Queue
enQueue(q, 14);
enQueue(q, 22);
enQueue(q, 6);
// Display elements present in Circular Queue
displayQueue(q);
// Deleting elements from Circular Queue
System.out.printf("\nDeleted value = %d", deQueue(q));
System.out.printf("\nDeleted value = %d", deQueue(q));
// Remaining elements in Circular Queue
displayQueue(q);
enQueue(q, 9);
enQueue(q, 20);
displayQueue(q);
}
}

View File

@ -1,78 +0,0 @@
// Java program for linked-list implementation of queue
// A linked list (LL) node to store a queue entry
class QNode {
int key;
QNode next;
// constructor to create a new linked list node
public QNode(int key)
{
this.key = key;
this.next = null;
}
}
// A class to represent a queue
// The queue, front stores the front node of LL and rear stores the
// last node of LL
class Queue {
QNode front, rear;
public Queue()
{
this.front = this.rear = null;
}
// Method to add an key to the queue.
void enqueue(int key)
{
// Create a new LL node
QNode temp = new QNode(key);
// If queue is empty, then new node is front and rear both
if (this.rear == null) {
this.front = this.rear = temp;
return;
}
// Add the new node at the end of queue and change rear
this.rear.next = temp;
this.rear = temp;
}
// Method to remove an key from queue.
void dequeue()
{
// If queue is empty, return NULL.
if (this.front == null)
return;
// Store previous front and move front one node ahead
QNode temp = this.front;
this.front = this.front.next;
// If front becomes NULL, then change rear also as NULL
if (this.front == null)
this.rear = null;
}
}
// Driver class
public class Test {
public static void main(String[] args)
{
Queue q = new Queue();
q.enqueue(10);
q.enqueue(20);
q.dequeue();
q.dequeue();
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.dequeue();
System.out.println("Queue Front : " + q.front.key);
System.out.println("Queue Rear : " + q.rear.key);
}
}

View File

@ -7,7 +7,3 @@
### Golang
1. [Interval Scheduling](go/interval-scheduling.go)
### Java
1. [Multi-Level Queue Scheduling](java/multi-level-queue-scheduling.java)
2. [Round Robin Scheduling](java/round-robin.java)

View File

@ -8,12 +8,6 @@
4. [finding squareroot using binary search](c-or-cpp/sqrt-monotonic-binary-search.cpp)
5. [Interpolation Search](c-or-cpp/interpolation-search.cpp)
### Java
1. [Linear Search](java/linear-search.java)
2. [Binary Search](java/binary-search.java)
3. [Jump Search](java/jump-search.java)
### Golang
1. [Linear Search](go/linear-search.go)

View File

@ -1,47 +0,0 @@
// Java implementation of recursive Binary Search
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);
}
}
// For running in terminal rename this file to BinarySearch.java
//then run the commands <javac BinarySearch.java> followed by <java BinarySearch>
//It will generate and a BinarySearch.class file which is a file containing java bytecode that is executed by JVM.

View File

@ -1,55 +0,0 @@
// Java program to implement Jump Search.
public class JumpSearch
{
public static int jumpSearch(int[] arr, int x)
{
int n = arr.length;
// Finding block size to be jumped
int step = (int)Math.floor(Math.sqrt(n));
// Finding the block where element is
// present (if it is present)
int prev = 0;
while (arr[Math.min(step, n)-1] < x)
{
prev = step;
step += (int)Math.floor(Math.sqrt(n));
if (prev >= n)
return -1;
}
// Doing a linear search for x in block
// beginning with prev.
while (arr[prev] < x)
{
prev++;
// If we reached next block or end of
// array, element is not present.
if (prev == Math.min(step, n))
return -1;
}
// If element is found
if (arr[prev] == x)
return prev;
return -1;
}
// Driver program to test function
public static void main(String [ ] args)
{
int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21,
34, 55, 89, 144, 233, 377, 610};
int x = 55;
// Find the index of 'x' using Jump Search
int index = jumpSearch(arr, x);
// Print the index where 'x' is located
System.out.println("\nNumber " + x +
" is at index " + index);
}
}

View File

@ -1,21 +0,0 @@
//Linear search to check for a given key in an array
public class MyLinearSearch{
public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String args[]){
int[] arr1= {10,20,30,50,70,90};
int key = 30;
System.out.println(key+" is present and is found at index: "+linearSearch(arr1, key));
}
}
// For running in terminal rename this file to MyLinearSearch.java
//then run the commands <javac MyLinearSearch.java> followed by <java MyLinearSearch>
//It will generate and a MyLinearSearch.class file which is a file containing java bytecode that is executed by JVM.

View File

@ -15,20 +15,6 @@
11. [Comb Sort](c-or-cpp/comb-sort.cpp)
12. [3 Way Quick Sort](c-or-cpp/3way_quick_sort.cpp)
### Java
1. [Bubble Sort](java/bubble-sort.java)
2. [Insertion Sort](java/insertion-sort.java)
3. [Selection Sort](java/selection-sort.java)
4. [Merge Sort](java/merge-sort.java)
5. [Quick Sort](java/quick-sort.java)
6. [Counting Sort](java/counting-sort.java)
7. [Bubble Sort algo](java/bubble-sort.java)
8. [Heap Sort Algo](java/heap-sort.java)
9. [Insertion Sort algo](java/insertion-sort.java)
10. [Selection Sort algo](java/selection-sort.java)
### Golang
1. [Insertion Sort](go/insertion-sort.go)
2. [Quick Sort](go/quick-sort.go)

View File

@ -1,27 +0,0 @@
import java.util.Arrays;
public class BubbleSort {
static int temp = 0;
static int[] nums = { 13, 34, 12, 45, 56, 32, 20 };
public static void main(String[] args) {
System.out.println("Before Sorting : "+Arrays.toString(nums));
sort();
}
//create method sorting array
public static void sort() {
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] > nums[i]) {
temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
}
}
}
System.out.println(Arrays.toString(nums));
}
}

View File

@ -1,74 +0,0 @@
public class CountingSort {
/**
* Public method to use the counting sort algorithm
* @param arr - the array in input
*/
public void sort(int[] arr){
int[] sortedArray = new int[arr.length + 1];
// Search max element
int max = arr[0];
for(int i = 0; i < arr.length; i++){
if(arr[i] > max){
max = arr[i];
}
}
// Create counting array
int[] countArray = new int[max + 1];
for(int i = 0; i < countArray.length; i++){
countArray[i] = 0;
}
// Count elements in array
for(int i = 0; i < arr.length; i++){
countArray[arr[i]]++;
}
for(int i = 1; i < countArray.length; i++){
countArray[i] += countArray[i - 1];
}
for (int i = arr.length - 1; i >= 0; i--) {
sortedArray[countArray[arr[i]] - 1] = arr[i];
countArray[arr[i]]--;
}
System.arraycopy(sortedArray, 0, arr, 0, arr.length);
}
/**
* Main method for testing
* @param args
*/
public static void main(String[] args) throws Exception {
CountingSort count = new CountingSort();
int[] test = {1,9,8,7,6,5,4,3,2,12,546,23,123,5768,689,45,6342,0,76,856,34,412,12,32,353,46,568,456,234,3456,467,345345,345,345,};
count.sort(test);
for(int i = 1; i < test.length; i++){
if(test[i] < test[i - 1]){
throw new Exception("[ERROR] Ops! Counting sort not work!");
}
}
printArray(test);
}
/**
* Print an array
* @param arr
*/
public static void printArray(int[] arr){
System.out.println("Sorted array: ");
for(int i = 0; i < arr.length; i++){
System.out.println(" " + i);
}
}
}

View File

@ -1,69 +0,0 @@
import java.util.Scanner;
public class HeapSort
{
public void sort(int array[])
{
int n = array.length;
for (int i = n / 2 - 1; i >= 0; i--)
heapify(array, n, i);
for (int i = n-1; i >= 0; i--)
{
int temp = array[0];
array[0] = array[i];
array[i] = temp;
heapify(array, i, 0);
}
}
void heapify(int array[], int n, int i)
{
int largest = i;
int l = 2*i + 1;
int r = 2*i + 2;
if (l < n && array[l] > array[largest])
largest = l;
if (r < n && array[r] > array[largest])
largest = r;
if (largest != i)
{
int swap = array[i];
array[i] = array[largest];
array[largest] = swap;
heapify(array, n, largest);
}
}
public static void main(String args[])
{
System.out.println("enter the array size");
Scanner inputobj = new Scanner(System.in);
int s = inputobj.nextInt();
int array[] = new int[s];
System.out.println("enter " + s + "elements of array");
for(int k=0;k<s;k++)
{
int e = inputobj.nextInt();
array[k] = e;
}
HeapSort ob = new HeapSort();
ob.sort(array);
System.out.println("Sorted array is");
for (int i=0; i<s; ++i)
System.out.print(array[i]+" ");
System.out.println();
}
}

View File

@ -1,29 +0,0 @@
import java.util.Arrays;
public class InsertionSort {
static int[] nums = { 12, 43, 2, 4, 1, 0, -23, -93 };
public static void main(String[] args) {
System.out.println("Before sorting " + Arrays.toString(nums));
sort(nums);
}
public static void sort(int[] nums) {
int i = 1;
while (i < nums.length) {
int temp, j;
temp = nums[i];
j = i;
while (j > 0 && nums[j - 1] > temp) {
nums[j] = nums[j - 1];
j--;
}
nums[j] = temp;
i++;
}
System.out.println("After Sorting " + Arrays.toString(nums));
}
}

View File

@ -1,79 +0,0 @@
//Java program for implementation of Merge Sort
import java.util.*;
class MergeSortApp
{
private int[] arr;
public MergeSortApp()
{
arr = new int[]{12,54,222,54622,10,169,30}; //Array to sort
}
//Function to display/Print Array
public void printArray()
{
for (int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+ " ");
}
System.out.println();
}
//Function called by main()
public void mergesort()
{
int[] wr = new int[arr.length]; //Provides workspace
recMergeSort(wr,0,wr.length-1);
}
//Recursive function to divide array in halves
public void recMergeSort(int[] wr,int lowBound,int uppBound)
{
if (lowBound == uppBound)
return;
else
{
int mid = (lowBound+uppBound)/2; //find midpoint
recMergeSort(wr,lowBound,mid); //Sort low half
recMergeSort(wr,mid+1,uppBound); // Sort high half
merge(wr,lowBound,mid+1,uppBound); //merge them
}
}
//Function to merge sorted Arrays
public void merge(int[] wr,int lowptr,int highptr, int uppBound)
{
int j=0;
int lowBound = lowptr;
int mid = highptr-1;
int n = uppBound-lowBound+1;
while (lowptr<=mid && highptr<=uppBound)
{ if (arr[lowptr]<arr[highptr])
wr[j++] = arr[lowptr++];
else
wr[j++] = arr[highptr++];
}
while (lowptr<=mid)
wr[j++] = arr[lowptr++];
while(highptr<=uppBound)
wr[j++] = arr[highptr++];
for (j=0;j<n;j++)
arr[lowBound+j] = wr[j];
}
}
class MergeSort
{ //Driver code to test above code
public static void main(String[] args)
{
MergeSortApp ob = new MergeSortApp(); //creates object
ob.printArray(); //Displays Array before sorting
ob.mergesort();
ob.printArray();
}
}

View File

@ -1,81 +0,0 @@
// Java program for implement Quick Sort
//Note: Rightmost element in the array is chosen as pivot
class QuickSortBack
{
private int[] arr;
public QuickSortBack()
{
arr = new int[]{222,64,545,99,12,35,1,87,33,945,77}; // Array to be sorted
}
//Function to swap two Array elements
public void swap(int index1 , int index2)
{
int x = arr[index1]; //first value in temporary variable x
arr[index1] = arr[index2];
arr[index2] = x;
}
//Function to print the Array
public void displayArray()
{
for (int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
// Function to partition the Array
public int partitionFn(int left,int right,int pivot)
{
int leftptr = left -1;
int rightptr = right;
while (true)
{
while (arr[++leftptr]<pivot); //Find bigger item than pivot
while (rightptr>0 && arr[--rightptr]>pivot); //Find smaller item
if (leftptr>=rightptr) //if index numbers cross,partition is done
break;
else
swap(leftptr,rightptr); //swap elements
}
swap(leftptr,right); //restore pivot element
return leftptr; //return pivot location
}
//Recursive quicksort function
public void recQuickSort(int left,int right)
{
if (right-left <= 0) // already sorted if size is 1
return;
else
{
int pivot = arr[right]; //choosing pivot as rightmost(end) element of Array
int partition = partitionFn(left,right,pivot);
recQuickSort(left,partition-1); //Sort left
recQuickSort(partition+1,right); //Sort right
}
}
//function called in main
public void quickSort()
{
recQuickSort(0,arr.length-1);
}
}
class QuickSort
{
//Driver code to test above
public static void main(String[] args) {
QuickSortBack ob = new QuickSortBack();
ob.displayArray(); //display array before sort
ob.quickSort(); //call quickSort
ob.displayArray();
}
}

View File

@ -1,50 +0,0 @@
class Selection
{
int minIndex(int Array[] , int start, int end)
{
int minIndex = start;
for (int i = start+1; i < end; i++)
{
if ( Array[i] < Array[minIndex] )
{
minIndex = i;
}
}
return minIndex;
}
int[] sorting(int Array[],int length)
{
for (int i = 0; i < length-1; i++)
{
int minI = minIndex(Array, i, length);
int temp = Array[minI];
Array[minI] = Array[i];
Array[i] = temp;
}
return Array;
}
}
/**
* SelectionSort
*/
public class SelectionSort {
public static void main(String[] args) {
int Array[] = {1,2,3,4,5,6,7,8,9};
Selection s1 = new Selection();
long startTime = System.nanoTime();
int sortedArray[] = s1.sorting(Array, 9);
long endTime = System.nanoTime();
for (int i = 0; i < 9; i++) {
System.out.println(sortedArray[i]);
}
System.out.println("Total Time in Neno Second: "+ (endTime-startTime));
}
}

View File

@ -3,9 +3,3 @@
### C or C++
1. [Balanced Parenthesis](c-or-cpp/balanced-parenthesis.cpp)
### Java
1. [Stack Implementation](java/stack.java)
2. [Balanced Parenthesis](java/balanced-paranthesis.java)
3. [Stock Span Problem](java/the-stock-span-problem.java)

View File

@ -1,69 +0,0 @@
import java.util.Iterator;
import java.util.Stack;
import java.util.Vector;
class Balanced_Paranthesis {
public void problem(String input_string){
Vector<String> output = new Vector<>();
Stack<Character> sta = new Stack<>();
for(int i = 0;i < input_string.length();i++){
for (int j = 0; j <= i; j++){
String sub_s = input_string.substring(j,i+1);
char[] sub = sub_s.toCharArray();
int no_of_left_paranthesis = 0;
int no_of_right_paranthesis = 0;
for (int k = 0;k < sub_s.length();k++){
if(sub[k] == '('){
no_of_left_paranthesis = no_of_left_paranthesis + 1;
sta.push('(');
}
if(sub[k] == ')'){
no_of_right_paranthesis = no_of_right_paranthesis + 1;
sta.pop();
}
if (sub_s.length() % 2 == 0 && no_of_left_paranthesis == no_of_right_paranthesis && sta.isEmpty()){
output.add(sub_s);
}
else{
while (!sta.isEmpty()){
sta.pop();
}
}
}
}
int length = 0;
if (output.size() == 0){
System.out.println(length + " ");
}
else{
int max_len = 0;
String long_Str = "";
for(int s = 0;s < output.size();s++){
if (output.get(s).length() > max_len){
max_len = output.get(s).length();
long_Str = output.get(s);
}
}
System.out.println("Maximum length of string : " + max_len + "and the string is : " + long_Str);
}
}
}
}
class Main {
public static void main(String[] args){
Balanced_Paranthesis bal = new Balanced_Paranthesis();
bal.problem("((()))");
}
}

View File

@ -1,93 +0,0 @@
class stack {
public int Max;
public int Top;
public int[] stack;
public stack(int Max){
this.Max = Max;
stack = new int[Max];
Top = -1;
}
/**
* if the stack is empty then always the top will be -1
* so this should return a boolean if value of top < 1 then returns true which means
* stack is empty.
*/
public boolean isEmpty(){
return (Top < 0);
}
public int size(){
return (Top+1);
}
public void push(int x){
if (size() >= Max){
System.out.println("Stack Overflow");
}
else{
Top = Top + 1;
stack[Top] = x;
}
}
/**
* pop function pops out the top element in the queue
* returns the element that is popped out of the queue
*/
public int pop(){
if (size() == 0){
System.out.println("Stack Empty Exception");
}
else {
/**
* the top element in the stack will be popped out from the stack
*/
int popped_element = stack[Top];
Top = Top - 1;
return popped_element;
}
return -1;
}
public int top(){
if(isEmpty()){
System.out.println("Stack Empty Exception");
}
else{
return stack[Top];
}
return -1;
}
public void PrintStack(){
if (isEmpty()){
System.out.println("Empty");
}
else{
for(int i = 0;i < size();i++){
System.out.print(stack[i] + " ");
}
System.out.println();
}
}
}
class Main {
public static void main(String[] args){
max = 1000;
stack object = new stack(max);
object.push(1);
object.push(2);
object.push(3);
object.pop();
object.top();
object.PrintStack();
}
}

View File

@ -1,98 +0,0 @@
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Stack ;
/**
* Problem statement :
* The stock span problem is a financial problem where we have a series of n daily price quotes for a stock
* and we need to calculate span of stocks price for all n days.
* The span Si of the stocks price on a given day i is defined as the maximum number of consecutive days just before the given day,
* for which the price of the stock on
* the current day is less than or equal to its price on the given day.
* For example, if an array of 7 days prices is given as {100, 80, 60, 70, 60, 75, 85}, then the span values for corresponding
* 7 days are {1, 1, 1, 2, 1, 4, 6}
*/
class The_Stock_Span_Problem extends stack{
public The_Stock_Span_Problem(int Max) {
super(Max);
}
/**
* this problem is being solved with stack abstract data type.
*/
public void problem(int[] price,int n,int[] span){
stack st = new stack(Max);
st.push(0);
//span of the first day is always going to be 1
span[0] = 1;
for (int i = 1;i < n;i ++){
span[i] = 1;
st.PrintStack();
while(!st.isEmpty() && price[st.top()] <= price[i]){
st.pop();
}
if (st.isEmpty()){
span[i] = i + 1;
}
else{
span[i] = i - st.top();
}
st.push(i);
}
printArray(span);
}
public void printArray(int[] span){
System.out.println("The span of the stock array :" + Arrays.toString(span));
}
/**
* This is a different approach that has slightly higher time complexity than the approach used above
* Both the methods are awesome and star struck but...xD
*/
public void alternate_approach(int[] price,int n,int[] span){
Stack<Integer> sta = new Stack<>();
span[0] = 1;
for (int i = 1;i < n;i++){
for (int j = 0;j < i;j++){
sta.push(j);
}
while(!sta.isEmpty() && price[sta.peek()] <= price[i]){
sta.pop();
}
if (sta.isEmpty()){
span[i] = i + 1;
}
else{
span[i] = i - sta.peek();
}
sta.clear();
}
printArray(span);
}
}
class Main {
//to test the span stock problem
public static void main(String[] args){
int[] price = { 10, 4, 5, 90, 120, 80 };
int n = price.length;
int[] span = new int[n];
The_Stock_Span_Problem prob = new The_Stock_Span_Problem(1000);
prob.alternate_approach(price,n,span);
}
}

View File

@ -11,14 +11,6 @@
7. [Permutation of String](c-or-cpp/Permutation-of-String.c)
8. [Count Words](c-or-cpp/count-words.c)
### Java
1. [Palindrome Check](java/palindrome.java)
2. [All subsequences](java/sequence.java)
3. [KMP String Searching](java/kmp.cpp)
4. [Rabin Karp String Searching](java/rabin-karp.cpp)
5. [String Tokenizer](java/tokenizer.java)
### Rust
1. [Palindrome Check](rust/palindrome/README.md)

View File

@ -1,35 +0,0 @@
//Separate the strings such as in other group same letter does not repeat.
//Example abcdaef will give 5,1,1 from first 'a' to last 'a' one group and then remaining 2 letters from 1-1 group
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class SplitString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string");
String s = sc.next();
List<Integer> a = new ArrayList<Integer>();
Map<Character, Integer> last = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
last.put(s.charAt(i), i);
}
int p = 0, ctr = 0;
for (int i = 0; i < s.length(); i++) {
if (last.get(s.charAt(i)) > p)
p = last.get(s.charAt(i));
++ctr;
if (i == p) {
a.add(ctr);
ctr = 0;
}
}
for (Integer i : a) {
System.out.println(i);
}
sc.close();
}
}

View File

@ -1,82 +0,0 @@
class KMP_String_Matching {
void KMPSearch(String pat, String txt)
{
int M = pat.length();
int N = txt.length();
// create lps[] that will hold the longest
// prefix suffix values for pattern
int lps[] = new int[M];
int j = 0; // index for pat[]
// Preprocess the pattern (calculate lps[]
// array)
computeLPSArray(pat, M, lps);
int i = 0; // index for txt[]
while (i < N) {
if (pat.charAt(j) == txt.charAt(i)) {
j++;
i++;
}
if (j == M) {
System.out.println("Found pattern "
+ "at index " + (i - j));
j = lps[j - 1];
}
// mismatch after j matches
else if (i < N && pat.charAt(j) != txt.charAt(i)) {
// Do not match lps[0..lps[j-1]] characters,
// they will match anyway
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
}
void computeLPSArray(String pat, int M, int lps[])
{
// length of the previous longest prefix suffix
int len = 0;
int i = 1;
lps[0] = 0; // lps[0] is always 0
// the loop calculates lps[i] for i = 1 to M-1
while (i < M) {
if (pat.charAt(i) == pat.charAt(len)) {
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
// This is tricky. Consider the example.
// AAACAAAA and i = 7. The idea is similar
// to search step.
if (len != 0) {
len = lps[len - 1];
// Also, note that we do not increment
// i here
}
else // if (len == 0)
{
lps[i] = len;
i++;
}
}
}
}
// Driver program to test above function
public static void main(String args[])
{
String txt = "ABABDABACDABABCABAB";
String pat = "ABABCABAB";
new KMP_String_Matching().KMPSearch(pat, txt);
}
}
// This code has been contributed by Amit Khandelwal.

View File

@ -1,56 +0,0 @@
public class palindrome {
// Function that returns true if
// str is a palindrome
static boolean isPalindrome(String str)
{
// Pointers pointing to the beginning
// and the end of the string
int i = 0, j = str.length() - 1;
// While there are characters toc compare
while (i < j) {
// If there is a mismatch
if (str.charAt(i) != str.charAt(j))
return false;
// Increment first pointer and
// decrement the other
i++;
j--;
}
// Given string is a palindrome
return true;
}
//new approach with case sensitive
public static boolean isPalindrome(String str, boolean caseSensitive){
// lowercase if not case sensitive
if(!caseSensitive) str = str.toLowerCase();
for(int i = 0; i < str.length() / 2; i++)
if(str.charAt(i) != str.charAt(str.length() - 1 - i))
return false;
return true;
}
// Driver code
public static void main(String[] args)
{
String str = "Dad";
if (isPalindrome(str))
System.out.println("Yes");
else
System.out.println("No");
if (isPalindrome(str, false))
System.out.println("Yes");
else
System.out.println("No");
}
}

View File

@ -1,78 +0,0 @@
public class Main
{
// d is the number of characters in the input alphabet
public final static int d = 256;
/* pat -> pattern
txt -> text
q -> A prime number
*/
static void search(String pat, String txt, int q)
{
int M = pat.length();
int N = txt.length();
int i, j;
int p = 0; // hash value for pattern
int t = 0; // hash value for txt
int h = 1;
// The value of h would be "pow(d, M-1)%q"
for (i = 0; i < M-1; i++)
h = (h*d)%q;
// Calculate the hash value of pattern and first
// window of text
for (i = 0; i < M; i++)
{
p = (d*p + pat.charAt(i))%q;
t = (d*t + txt.charAt(i))%q;
}
// Slide the pattern over text one by one
for (i = 0; i <= N - M; i++)
{
// Check the hash values of current window of text
// and pattern. If the hash values match then only
// check for characters on by one
if ( p == t )
{
/* Check for characters one by one */
for (j = 0; j < M; j++)
{
if (txt.charAt(i+j) != pat.charAt(j))
break;
}
// if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]
if (j == M)
System.out.println("Pattern found at index " + i);
}
// Calculate hash value for next window of text: Remove
// leading digit, add trailing digit
if ( i < N-M )
{
t = (d*(t - txt.charAt(i)*h) + txt.charAt(i+M))%q;
// We might get negative value of t, converting it
// to positive
if (t < 0)
t = (t + q);
}
}
}
/* Driver Code */
public static void main(String[] args)
{
String txt = "ABCAMCABAMMAM";
String pat = "AM";
// A prime number
int q = 101;
// Function Call
search(pat, txt, q);
}
}

View File

@ -1,28 +0,0 @@
import java.util.*;
class sequence {
static List<String> al = new ArrayList<>();
public static void main(String[] args)
{
String s = "abc";
findsubsequences(s, "");
System.out.println(al);
}
private static void findsubsequences(String s,
String ans)
{
if (s.length() == 0) {
al.add(ans);
return;
}
findsubsequences(s.substring(1), ans + s.charAt(0));
findsubsequences(s.substring(1), ans);
}
}

View File

@ -1,96 +0,0 @@
import java.util.ArrayList;
import java.util.List;
public class tokenizer{
public static boolean charIsDelimiter(char c, char [] delimiters){
//verrify if a character is a delimiter
for(char d: delimiters)
if(c == d) return true;
return false;
}
public static List<String> tokenize(String str, char... delimiters){
//by default the delimiter is white space ' '
if(delimiters.length <= 0) delimiters = new char [] {' '};
List<String> tokens = new ArrayList<String>();
String token = "";
for(int i = 0; i < str.length(); i++) {
char pos = str.charAt(i);
if(!charIsDelimiter(pos, delimiters)) {
//if the character is not a delimiter add it into the current token
token += pos;
}else {
//avoid an empty token before adding to the list
if(!token.equals(""))
tokens.add(token);
token = "";
}
}
//add the last token to the list
tokens.add(token);
return tokens;
}
public static void printTokens(List<String> tokens){
if(tokens == null) return;
System.out.print("[ ");
for(String token : tokens){
System.out.print("'" + token + "', ");
}
System.out.println("]");
}
public static void main(String [] args){
String myString = "Hello I like pasta & pizza--hut";
System.out.println("myString = '" + myString + "'");
System.out.print("\ntokenize(myString) = ");
printTokens(tokenize(myString));
System.out.print("\ntokenize(myString, ' ', 'z') = ");
printTokens(tokenize(myString, ' ', 'z'));
System.out.print("\ntokenize(myString, 'p','l', 'u') = ");
printTokens(tokenize(myString, 'p','l', 'u'));
System.out.print("\ntokenize(myString, ' ', '&', '-') = ");
printTokens(tokenize(myString, ' ', '&', '-'));
}
}
/*
to call the function:
tokenize(str, delimiters)
str is a text
delimiters is a list of char which is by default white space : ' '
example:
tokenize("hello world") = tokenize("hello world", ' ') = [ 'hello', 'world' ]
tokenize("hello world", ' ', 'l') = [ 'he', 'o', 'wor', 'd' ]
to run this file:
javac tokenizer.java
java tokenizer
result:
myString = 'Hello I like pasta & pizza--hut'
tokenize(myString) = [ 'Hello', 'I', 'like', 'pasta', '&', 'pizza--hut', ]
tokenize(myString, ' ', 'z') = [ 'Hello', 'I', 'like', 'pasta', '&', 'pi', 'a--hut', ]
tokenize(myString, 'p','l', 'u') = [ 'He', 'o I ', 'ike ', 'asta & ', 'izza--h', 't', ]
tokenize(myString, ' ', '&', '-') = [ 'Hello', 'I', 'like', 'pasta', 'pizza', 'hut', ]
*/

View File

@ -7,7 +7,3 @@
3. [Build Binary Tree using Pre,In & Post Order](c-or-cpp/build-binary-tree.cpp)
4. [Count and find the Sum of nodes in a Binary Tree](c-or-cpp/count-and-sum-of-nodes-in-binary-tree.cpp)
### Java
1. [Pre, In & Post Order Traversals](java/pre_in_post_traversal.java)

View File

@ -1,76 +0,0 @@
class Node{
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
}
public class pre_in_post_traversal{
public static void preOrder(Node node){
if (node == null) return;
System.out.print(node.value + ", ");
preOrder(node.left);
preOrder(node.right);
}
public static void inOrder(Node node){
if(node == null) return;
inOrder(node.left);
System.out.print(node.value + ", ");
inOrder(node.right);
}
public static void postOrder(Node node){
if(node == null) return;
postOrder(node.left);
postOrder(node.right);
System.out.print(node.value + ", ");
}
public static void main(String [] args){
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(7);
root.left.right = new Node(6);
root.left.left = new Node(1);
root.right.right = new Node(9);
System.out.print("pre order: ");
preOrder(root);
System.out.println("\n");
System.out.print("in order: ");
inOrder(root);
System.out.print("\n\npost order: ");
postOrder(root);
}
}
/*
tree structure:
4
/ \
2 7
/ \ \
1 6 9
to run the file:
javac .\pre_in_post_traversal.java
java pre_in_post_traversal
results:
pre order: 4, 2, 1, 6, 7, 9,
in order: 1, 2, 6, 4, 7, 9,
post order: 1, 6, 2, 9, 7, 4,
*/