commit
75c55b8ce7
7
.classpath
Normal file
7
.classpath
Normal file
@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry excluding="data_structures/" kind="src" path=""/>
|
||||
<classpathentry kind="src" path="data_structures"/>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
|
||||
<classpathentry kind="output" path="bin"/>
|
||||
</classpath>
|
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
/bin/
|
17
.project
Normal file
17
.project
Normal file
@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>Java</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.jdt.core.javabuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||
</natures>
|
||||
</projectDescription>
|
@ -1,53 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
class BinarySearch
|
||||
{
|
||||
public static int BS(int array[], int key, int lb, int ub)
|
||||
{
|
||||
if (lb>ub)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
int mid=(lb+ub)/2;
|
||||
|
||||
if (key<array[mid])
|
||||
{
|
||||
return (BS(array, key, lb, mid-1));
|
||||
}
|
||||
else if (key>array[mid])
|
||||
{
|
||||
return (BS(array, key, mid+1, ub));
|
||||
}
|
||||
else
|
||||
{
|
||||
return mid;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner input=new Scanner(System.in);
|
||||
int array[]=new int[10] ;
|
||||
int key;
|
||||
|
||||
//Input
|
||||
System.out.println("Enter an array of 10 numbers : ");
|
||||
for (int i=0; i<10 ;i++ )
|
||||
{
|
||||
array[i]=input.nextInt();
|
||||
}
|
||||
System.out.println("Enter the number to be searched : ");
|
||||
key=input.nextInt();
|
||||
|
||||
int index=BS(array, key, 0, 9);
|
||||
if (index!=-1)
|
||||
{
|
||||
System.out.println("Number found at index number : " + index);
|
||||
}
|
||||
else
|
||||
{
|
||||
System.out.println("Not found");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,38 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
class BubbleSort
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
int array[]=new int[6];
|
||||
Scanner input=new Scanner(System.in);
|
||||
|
||||
//Input
|
||||
System.out.println("Enter any 6 Numbers for Unsorted Array : ");
|
||||
for(int i=0; i<6; i++)
|
||||
{
|
||||
array[i]=input.nextInt();
|
||||
}
|
||||
|
||||
//Sorting
|
||||
for(int i=0; i<6; i++)
|
||||
{
|
||||
for(int j=0; j<5; j++)
|
||||
{
|
||||
if(array[j]>array[j+1])
|
||||
{
|
||||
int temp=array[j];
|
||||
array[j]=array[j+1];
|
||||
array[j+1]=temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Output
|
||||
for(int i=0; i<6; i++)
|
||||
{
|
||||
System.out.print(array[i]+"\t");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
59
Conversions/AnyBaseToDecimal.java
Normal file
59
Conversions/AnyBaseToDecimal.java
Normal file
@ -0,0 +1,59 @@
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
// Driver program
|
||||
public class AnyBaseToDecimal {
|
||||
public static void main (String[] args) throws Exception{
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||
|
||||
String inp = br.readLine();
|
||||
int base = Integer.parseInt(br.readLine());
|
||||
|
||||
System.out.println("Input in base " + base + " is: " + inp);
|
||||
System.out.println("Decimal value of " + inp + " is: " + convertToDecimal(inp, base));
|
||||
|
||||
br.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method produces a decimal value of any given input number of any base
|
||||
* @param inp_num String of which we need the decimal value and base in integer format
|
||||
* @return string format of the decimal value
|
||||
*/
|
||||
|
||||
public static String convertToDecimal(String inp_num, int base) {
|
||||
int len = inp_num.length();
|
||||
int num = 0;
|
||||
int pow = 1;
|
||||
|
||||
for (int i=len-1; i>=0; i--) {
|
||||
if (valOfChar(inp_num.charAt(i)) >= base) {
|
||||
return "Invalid Number";
|
||||
}
|
||||
num += valOfChar(inp_num.charAt(i))*pow;
|
||||
pow *= base;
|
||||
}
|
||||
return String.valueOf(num);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method produces integer value of the input character and returns it
|
||||
* @param c Char of which we need the integer value of
|
||||
* @return integer value of input char
|
||||
*/
|
||||
|
||||
public static int valOfChar(char c) {
|
||||
if (c >= '0' && c <= '9') {
|
||||
return (int)c - '0';
|
||||
}
|
||||
else {
|
||||
return (int)c - 'A' + 10;
|
||||
}
|
||||
}
|
||||
}
|
33
Conversions/BinaryToDecimal.java
Normal file
33
Conversions/BinaryToDecimal.java
Normal file
@ -0,0 +1,33 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* This class converts a Binary number to a Decimal number
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class BinaryToDecimal
|
||||
{
|
||||
|
||||
/**
|
||||
* Main Method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[])
|
||||
{
|
||||
Scanner sc=new Scanner(System.in);
|
||||
int n,k,d,s=0,c=0;
|
||||
System.out.print("Binary number: ");
|
||||
n=sc.nextInt();
|
||||
k=n;
|
||||
while(k!=0)
|
||||
{
|
||||
d=k%10;
|
||||
s+=d*(int)Math.pow(2,c++);
|
||||
k/=10;
|
||||
}
|
||||
System.out.println("Decimal equivalent:"+s);
|
||||
sc.close();
|
||||
}
|
||||
}
|
43
Conversions/BinaryToOctal.java
Normal file
43
Conversions/BinaryToOctal.java
Normal file
@ -0,0 +1,43 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Converts any Binary number to an Octal Number
|
||||
*
|
||||
* @author Zachary Jones
|
||||
*
|
||||
*/
|
||||
public class BinaryToOctal {
|
||||
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int b = sc.nextInt();
|
||||
System.out.println("Octal equivalent: " + convertBinaryToOctal(b));
|
||||
sc.close();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* This method converts a binary number to
|
||||
* an octal number.
|
||||
*
|
||||
* @param b The binary number
|
||||
* @return The octal number
|
||||
*/
|
||||
public static int convertBinaryToOctal(int b) {
|
||||
int o = 0, r=0, j =1 ;
|
||||
while(b!=0)
|
||||
{
|
||||
r = b % 10;
|
||||
o = o + r * j;
|
||||
j = j * 2;
|
||||
b = b / 10;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
}
|
65
Conversions/DecimalToAnyBase.java
Normal file
65
Conversions/DecimalToAnyBase.java
Normal file
@ -0,0 +1,65 @@
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
// Driver Program
|
||||
public class DecimalToAnyBase {
|
||||
public static void main (String[] args) throws Exception{
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||
System.out.println("Enter the decimal input below: ");
|
||||
int decInput = Integer.parseInt(br.readLine());
|
||||
System.out.println();
|
||||
|
||||
System.out.println("Enter the base below: ");
|
||||
int base = Integer.parseInt(br.readLine());
|
||||
System.out.println();
|
||||
|
||||
System.out.println("Decimal Input" + " is: " + decInput);
|
||||
System.out.println("Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base));
|
||||
|
||||
br.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method produces a String value of any given input decimal in any base
|
||||
* @param inp Decimal of which we need the value in base in String format
|
||||
* @return string format of the converted value in the given base
|
||||
*/
|
||||
|
||||
public static String convertToAnyBase(int inp, int base) {
|
||||
ArrayList<Character> charArr = new ArrayList<>();
|
||||
|
||||
while (inp > 0) {
|
||||
charArr.add(reVal(inp%base));
|
||||
inp /= base;
|
||||
}
|
||||
|
||||
StringBuilder str = new StringBuilder(charArr.size());
|
||||
|
||||
for(Character ch: charArr)
|
||||
{
|
||||
str.append(ch);
|
||||
}
|
||||
|
||||
return str.reverse().toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method produces character value of the input integer and returns it
|
||||
* @param num integer of which we need the character value of
|
||||
* @return character value of input integer
|
||||
*/
|
||||
|
||||
public static char reVal(int num) {
|
||||
if (num >= 0 && num <= 9)
|
||||
return (char)(num + '0');
|
||||
else
|
||||
return (char)(num - 10 + 'A');
|
||||
}
|
||||
}
|
32
Conversions/DecimalToBinary.java
Normal file
32
Conversions/DecimalToBinary.java
Normal file
@ -0,0 +1,32 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* This class converts a Decimal number to a Binary number
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class DecimalToBinary
|
||||
{
|
||||
/**
|
||||
* Main Method
|
||||
*
|
||||
* @param args Command Line Arguments
|
||||
*/
|
||||
public static void main(String args[])
|
||||
{
|
||||
Scanner sc=new Scanner(System.in);
|
||||
int n,k,s=0,c=0,d;
|
||||
System.out.print("Decimal number: ");
|
||||
n=sc.nextInt();
|
||||
k=n;
|
||||
while(k!=0)
|
||||
{
|
||||
d=k%2;
|
||||
s=s+d*(int)Math.pow(10,c++);
|
||||
k/=2;
|
||||
}//converting decimal to binary
|
||||
System.out.println("Binary equivalent:"+s);
|
||||
sc.close();
|
||||
}
|
||||
}
|
33
Conversions/DecimalToHexaDecimal.java
Normal file
33
Conversions/DecimalToHexaDecimal.java
Normal file
@ -0,0 +1,33 @@
|
||||
import java.lang.StringBuilder;
|
||||
import java.util.Scanner;
|
||||
|
||||
class Test {
|
||||
private static final int sizeOfIntInHalfBytes = 8;
|
||||
private static final int numberOfBitsInAHalfByte = 4;
|
||||
private static final int halfByte = 0x0F;
|
||||
private static final char[] hexDigits = {
|
||||
'0', '1', '2', '3', '4', '5', '6', '7',
|
||||
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
|
||||
};
|
||||
|
||||
public static String decToHex(int dec) {
|
||||
StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
|
||||
hexBuilder.setLength(sizeOfIntInHalfBytes);
|
||||
for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
|
||||
{
|
||||
int j = dec & halfByte;
|
||||
hexBuilder.setCharAt(i, hexDigits[j]);
|
||||
dec >>= numberOfBitsInAHalfByte;
|
||||
}
|
||||
return hexBuilder.toString();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.println("Write your Number to convert into HexaDecimal: ")
|
||||
int dec = 305445566;
|
||||
String hex = Integer.toHexString(dec);
|
||||
String hex = decToHex(dec);
|
||||
System.out.println(hex);
|
||||
}
|
||||
}
|
33
Conversions/DecimalToOctal.java
Normal file
33
Conversions/DecimalToOctal.java
Normal file
@ -0,0 +1,33 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* This class converts Decimal numbers to Octal Numbers
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Decimal_Octal
|
||||
{
|
||||
/**
|
||||
* Main Method
|
||||
*
|
||||
* @param args Command line Arguments
|
||||
*/
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner sc=new Scanner(System.in);
|
||||
int n,k,d,s=0,c=0;
|
||||
System.out.print("Decimal number: ");
|
||||
n=sc.nextInt();
|
||||
k=n;
|
||||
while(k!=0)
|
||||
{
|
||||
d=k%8;
|
||||
s+=d*(int)Math.pow(10,c++);
|
||||
k/=8;
|
||||
}
|
||||
|
||||
System.out.println("Octal equivalent:"+s);
|
||||
sc.close();
|
||||
}
|
||||
}
|
37
Conversions/HexaDecimalToBinary.java
Normal file
37
Conversions/HexaDecimalToBinary.java
Normal file
@ -0,0 +1,37 @@
|
||||
import java.lang.StringBuilder;
|
||||
import java.util.*;
|
||||
import java.util.Scanner;
|
||||
import javax.swing.*;
|
||||
|
||||
public class HexaToBin {
|
||||
|
||||
private final int LONG_BITS = 8;
|
||||
|
||||
public void convert(String numHex) {
|
||||
//String a HexaDecimal:
|
||||
int conHex = Integer.parseInt(numHex, 16);
|
||||
//Hex a Binary:
|
||||
String binary = Integer.toBinaryString(conHex);
|
||||
//Presentation:
|
||||
System.out.println(numHex + " = " + completeDigits(binary));
|
||||
}
|
||||
|
||||
public String completeDigits(String binNum) {
|
||||
for (int i = binNum.length(); i < LONG_BITS; i++) {
|
||||
binNum = "0" + binNum;
|
||||
}
|
||||
return binNum;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
//Testing Numbers:
|
||||
String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB",
|
||||
"19", "01", "02", "03", "04"};
|
||||
Convert objConvert = new Convert();
|
||||
|
||||
for (String num : hexNums) {
|
||||
objConvert.convert(num);
|
||||
}
|
||||
}
|
||||
}
|
49
Conversions/OctalToBinary.java
Normal file
49
Conversions/OctalToBinary.java
Normal file
@ -0,0 +1,49 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Converts any Octal number to a Binary number
|
||||
*
|
||||
* @author Zachary Jones
|
||||
*
|
||||
*/
|
||||
public class OctalToBinary {
|
||||
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int o = sc.nextInt();
|
||||
System.out.println("Binary equivalent: " + convertOctalToBinary(o));
|
||||
sc.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method converts an octal number
|
||||
* to a binary number.
|
||||
*
|
||||
* @param o The octal number
|
||||
* @return The binary number
|
||||
*/
|
||||
public static int convertOctalToBinary(int o) {
|
||||
Scanner scan;
|
||||
int num;
|
||||
|
||||
void getVal() {
|
||||
|
||||
System.out.println("Octal to Binary");
|
||||
scan = new Scanner(System.in);
|
||||
// Entering the needed number
|
||||
System.out.println("\nEnter the number : ");
|
||||
num = Integer.parseInt(scan.nextLine(), 8);
|
||||
}
|
||||
|
||||
void convert() {
|
||||
|
||||
String binary = Integer.toBinaryString(num);
|
||||
System.out.println("Binary Value is : " + binary);
|
||||
}
|
||||
}
|
||||
}
|
48
Conversions/OctalToDecimal.java
Normal file
48
Conversions/OctalToDecimal.java
Normal file
@ -0,0 +1,48 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Converts any Octal Number to a Decimal Number
|
||||
*
|
||||
* @author Zachary Jones
|
||||
*
|
||||
*/
|
||||
public class OctalToDecimal {
|
||||
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int o = sc.nextInt();
|
||||
System.out.println("Decimal equivalent: " + convertOctalToDecimal(o));
|
||||
sc.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method converts an octal number to
|
||||
* a decimal number.
|
||||
*
|
||||
* @param o The octal number
|
||||
* @return The decimal number
|
||||
*/
|
||||
public static int convertOctalToDecimal(int o) {
|
||||
System.out.print("Octal Input: ");
|
||||
// Read the input from the console which we are expecting as an octal number:
|
||||
Scanner s = new Scanner(System.in);
|
||||
String inputHex = s.nextLine();
|
||||
try{
|
||||
// Actual conversion of Octal to Decimal:
|
||||
Integer outputDecimal = Integer.parseInt(inputHex, 8);
|
||||
System.out.println("Decimal Equivalent : " + outputDecimal);
|
||||
}
|
||||
catch(NumberFormatException ne){
|
||||
// Printing a warning message if the input is not a valid octal number:
|
||||
System.out.println("Invalid Input, Expecting octal number 0-7");
|
||||
}
|
||||
finally{
|
||||
s.close();
|
||||
}
|
||||
}
|
||||
}
|
75
Dynamic Programming/Fibonacci.java
Normal file
75
Dynamic Programming/Fibonacci.java
Normal file
@ -0,0 +1,75 @@
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
public class Fibonacci {
|
||||
|
||||
public static Map<Integer,Integer> map = new HashMap<Integer,Integer>();
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||
int n = Integer.parseInt(br.readLine());
|
||||
|
||||
System.out.println(fibMemo(n)); // Returns 8 for n = 6
|
||||
System.out.println(fibBotUp(n)); // Returns 8 for n = 6
|
||||
}
|
||||
|
||||
/**
|
||||
* This method finds the nth fibonacci number using memoization technique
|
||||
*
|
||||
* @param n The input n for which we have to determine the fibonacci number
|
||||
* Outputs the nth fibonacci number
|
||||
**/
|
||||
|
||||
public static int fibMemo(int n) {
|
||||
if (map.containsKey(n)) {
|
||||
return map.get(n);
|
||||
}
|
||||
|
||||
int f;
|
||||
|
||||
if (n <= 2) {
|
||||
f = 1;
|
||||
}
|
||||
else {
|
||||
f = fib(n-1) + fib(n-2);
|
||||
map.put(n,f);
|
||||
}
|
||||
|
||||
return f;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method finds the nth fibonacci number using bottom up
|
||||
*
|
||||
* @param n The input n for which we have to determine the fibonacci number
|
||||
* Outputs the nth fibonacci number
|
||||
**/
|
||||
|
||||
public static int fibBotUp(int n) {
|
||||
|
||||
Map<Integer,Integer> fib = new HashMap<Integer,Integer>();
|
||||
|
||||
for (int i=1;i<n+1;i++) {
|
||||
int f = 1;
|
||||
if (i<=2) {
|
||||
f = 1;
|
||||
}
|
||||
else {
|
||||
f = fib.get(i-1) + fib.get(i-2);
|
||||
}
|
||||
fib.put(i, f);
|
||||
}
|
||||
|
||||
return fib.get(n);
|
||||
}
|
||||
}
|
||||
|
55
Dynamic Programming/Levenshtein_distance.java
Normal file
55
Dynamic Programming/Levenshtein_distance.java
Normal file
@ -0,0 +1,55 @@
|
||||
/**
|
||||
*
|
||||
* @author Kshitij VERMA (github.com/kv19971)
|
||||
* LEVENSHTEIN DISTANCE dyamic programming implementation to show the difference between two strings (https://en.wikipedia.org/wiki/Levenshtein_distance)
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
public class Levenshtein_distance{
|
||||
private int minimum(int a, int b, int c){
|
||||
if(a < b && a < c){
|
||||
return a;
|
||||
}else if(b < a && b < c){
|
||||
return b;
|
||||
}else{
|
||||
return c;
|
||||
}
|
||||
}
|
||||
public int calculate_distance(String a, String b){
|
||||
len_a = a.length() + 1;
|
||||
len_b = b.length() + 1;
|
||||
int [][] distance_mat = new int[len_a][len_b];
|
||||
for(int i = 0; i < len_a; i++){
|
||||
distance_mat[i][0] = i;
|
||||
}
|
||||
for(int j = 0; j < len_b; j++){
|
||||
distance_mat[0][j] = j;
|
||||
}
|
||||
for(int i = 0; i < len_a; i++){
|
||||
for(int j = 0; i < len_b; j++){
|
||||
int cost;
|
||||
if (a.charAt(i) == b.charAt(j)){
|
||||
cost = 0;
|
||||
}else{
|
||||
cost = 1;
|
||||
}
|
||||
distance_mat[i][j] = minimum(distance_mat[i-1][j], distance_mat[i-1][j-1], distance_mat[i][j-1]) + cost;
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
return distance_mat[len_a-1][len_b-1];
|
||||
|
||||
}
|
||||
public static void main(String [] args){
|
||||
String a = ""; // enter your string here
|
||||
String b = ""; // enter your string here
|
||||
|
||||
System.out.print("Levenshtein distance between "+a + " and "+b+ " is: ");
|
||||
System.out.println(calculate_distance(a,b));
|
||||
|
||||
|
||||
}
|
||||
}
|
62
Dynamic Programming/LongestIncreasingSubsequence.java
Normal file
62
Dynamic Programming/LongestIncreasingSubsequence.java
Normal file
@ -0,0 +1,62 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Afrizal Fikri (https://github.com/icalF)
|
||||
*
|
||||
*/
|
||||
public class LongestIncreasingSubsequence {
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int n = sc.nextInt();
|
||||
|
||||
int ar[] = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
ar[i] = sc.nextInt();
|
||||
}
|
||||
|
||||
System.out.println(LIS(ar));
|
||||
}
|
||||
|
||||
private static int upperBound(int[] ar, int l, int r, int key) {
|
||||
while (l < r-1) {
|
||||
int m = (l + r) / 2;
|
||||
if (ar[m] >= key)
|
||||
r = m;
|
||||
else
|
||||
l = m;
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
public static int LIS(int[] array) {
|
||||
int N = array.length;
|
||||
if (N == 0)
|
||||
return 0;
|
||||
|
||||
int[] tail = new int[N];
|
||||
int length = 1; // always points empty slot in tail
|
||||
|
||||
tail[0] = array[0];
|
||||
for (int i = 1; i < N; i++) {
|
||||
|
||||
// new smallest value
|
||||
if (array[i] < tail[0])
|
||||
tail[0] = array[i];
|
||||
|
||||
// array[i] extends largest subsequence
|
||||
else if (array[i] > tail[length-1])
|
||||
tail[length++] = array[i];
|
||||
|
||||
// array[i] will become end candidate of an existing subsequence or
|
||||
// Throw away larger elements in all LIS, to make room for upcoming grater elements than array[i]
|
||||
// (and also, array[i] would have already appeared in one of LIS, identify the location and replace it)
|
||||
else
|
||||
tail[upperBound(tail, -1, length-1, array[i])] = array[i];
|
||||
}
|
||||
|
||||
return length;
|
||||
}
|
||||
}
|
158
Huffman.java
Normal file
158
Huffman.java
Normal file
@ -0,0 +1,158 @@
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
import java.util.Stack;
|
||||
/**
|
||||
*
|
||||
* @author Mayank Kumar (mk9440)
|
||||
*/
|
||||
/*
|
||||
Output :
|
||||
|
||||
Enter number of distinct letters
|
||||
6
|
||||
Enter letters with its frequncy to encode
|
||||
Enter letter : a
|
||||
Enter frequncy : 45
|
||||
|
||||
Enter letter : b
|
||||
Enter frequncy : 13
|
||||
|
||||
Enter letter : c
|
||||
Enter frequncy : 12
|
||||
|
||||
Enter letter : d
|
||||
Enter frequncy : 16
|
||||
|
||||
Enter letter : e
|
||||
Enter frequncy : 9
|
||||
|
||||
Enter letter : f
|
||||
Enter frequncy : 5
|
||||
|
||||
Letter Encoded Form
|
||||
a 0
|
||||
b 1 0 1
|
||||
c 1 0 0
|
||||
d 1 1 1
|
||||
e 1 1 0 1
|
||||
f 1 1 0 0
|
||||
|
||||
*/
|
||||
|
||||
class Node{
|
||||
String letr="";
|
||||
int freq=0,data=0;
|
||||
Node left=null,right=null;
|
||||
}
|
||||
|
||||
//A comparator class to sort list on the basis of their frequency
|
||||
class comp implements Comparator<Node>{
|
||||
@Override
|
||||
public int compare(Node o1, Node o2) {
|
||||
if(o1.freq>o2.freq){return 1;}
|
||||
else if(o1.freq<o2.freq){return -1;}
|
||||
else{return 0;}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class Huffman {
|
||||
|
||||
// A simple function to print a given list
|
||||
//I just made it for debugging
|
||||
public static void print_list(List li){
|
||||
Iterator<Node> it=li.iterator();
|
||||
while(it.hasNext()){Node n=it.next();System.out.print(n.freq+" ");}System.out.println();
|
||||
}
|
||||
|
||||
//Function for making tree (Huffman Tree)
|
||||
public static Node make_huffmann_tree(List li){
|
||||
//Sorting list in increasing order of its letter frequency
|
||||
li.sort(new comp());
|
||||
Node temp=null;
|
||||
Iterator it=li.iterator();
|
||||
//System.out.println(li.size());
|
||||
//Loop for making huffman tree till only single node remains in list
|
||||
while(true){
|
||||
temp=new Node();
|
||||
//a and b are Node which are to be combine to make its parent
|
||||
Node a=new Node(),b=new Node();
|
||||
a=null;b=null;
|
||||
//checking if list is eligible for combining or not
|
||||
//here first assignment of it.next in a will always be true as list till end will
|
||||
//must have atleast one node
|
||||
a=(Node)it.next();
|
||||
//Below condition is to check either list has 2nd node or not to combine
|
||||
//If this condition will be false, then it means construction of huffman tree is completed
|
||||
if(it.hasNext()){b=(Node)it.next();}
|
||||
//Combining first two smallest nodes in list to make its parent whose frequncy
|
||||
//will be equals to sum of frequency of these two nodes
|
||||
if(b!=null){
|
||||
temp.freq=a.freq+b.freq;a.data=0;b.data=1;//assigining 0 and 1 to left and right nodes
|
||||
temp.left=a;temp.right=b;
|
||||
//after combing, removing first two nodes in list which are already combined
|
||||
li.remove(0);//removes first element which is now combined -step1
|
||||
li.remove(0);//removes 2nd element which comes on 1st position after deleting first in step1
|
||||
li.add(temp);//adding new combined node to list
|
||||
//print_list(li); //For visualizing each combination step
|
||||
}
|
||||
//Sorting after combining to again repeat above on sorted frequency list
|
||||
li.sort(new comp());
|
||||
it=li.iterator();//resetting list pointer to first node (head/root of tree)
|
||||
if(li.size()==1){return (Node)it.next();} //base condition ,returning root of huffman tree
|
||||
}
|
||||
}
|
||||
|
||||
//Function for finding path between root and given letter ch
|
||||
public static void dfs(Node n,String ch){
|
||||
Stack<Node> st=new Stack(); // stack for storing path
|
||||
int freq=n.freq; // recording root freq to avoid it adding in path encoding
|
||||
find_path_and_encode(st,n,ch,freq);
|
||||
}
|
||||
|
||||
//A simple utility function to print stack (Used for printing path)
|
||||
public static void print_path(Stack<Node> st){
|
||||
for(int i=0;i<st.size();i++){
|
||||
System.out.print(st.elementAt(i).data+" ");
|
||||
}
|
||||
}
|
||||
|
||||
public static void find_path_and_encode(Stack<Node> st,Node root,String s,int f){
|
||||
//Base condition
|
||||
if(root!= null){
|
||||
if(root.freq!=f){st.push(root);} // avoiding root to add in path/encoding bits
|
||||
if(root.letr.equals(s)){print_path(st);return;} // Recursion stopping condition when path gets founded
|
||||
find_path_and_encode(st,root.left,s,f);
|
||||
find_path_and_encode(st,root.right,s,f);
|
||||
//Popping if path not found in right or left of this node,because we previously
|
||||
//pushed this node in taking a mindset that it might be in path
|
||||
st.pop();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String args[]){
|
||||
List <Node> li=new LinkedList<>();
|
||||
Scanner in=new Scanner(System.in);
|
||||
System.out.println("Enter number of distinct letters ");
|
||||
int n=in.nextInt();
|
||||
String s[]=new String[n];
|
||||
System.out.print("Enter letters with its frequncy to encode\n");
|
||||
for(int i=0;i<n;i++){
|
||||
Node a=new Node();
|
||||
System.out.print("Enter letter : ");
|
||||
a.letr=in.next();s[i]=a.letr;
|
||||
System.out.print("Enter frequncy : ");
|
||||
a.freq=in.nextInt();System.out.println();
|
||||
li.add(a);
|
||||
}
|
||||
Node root=new Node();
|
||||
root=make_huffmann_tree(li);
|
||||
System.out.println("Letter\t\tEncoded Form");
|
||||
for(int i=0;i<n;i++){
|
||||
System.out.print(s[i]+"\t\t");dfs(root,s[i]);System.out.println();}
|
||||
}
|
||||
}
|
@ -1,38 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
class InsertionSort
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
int array[]=new int[6];
|
||||
Scanner input=new Scanner(System.in);
|
||||
|
||||
//Input
|
||||
System.out.println("Enter any 6 Numbers for Unsorted Array : ");
|
||||
for(int i=0; i<6; i++)
|
||||
{
|
||||
array[i]=input.nextInt();
|
||||
}
|
||||
|
||||
//Sorting
|
||||
for(int i=0; i<6; i++)
|
||||
{
|
||||
int temp=array[i];
|
||||
int j=i-1;
|
||||
while(j>=0 && temp<array[j] )
|
||||
{
|
||||
array[j+1]=array[j];
|
||||
j--;
|
||||
}
|
||||
|
||||
array[j+1]=temp;
|
||||
}
|
||||
|
||||
//Output
|
||||
for(int i=0; i<6; i++)
|
||||
{
|
||||
System.out.print(array[i]+"\t");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
43
Misc/CountChar.java
Normal file
43
Misc/CountChar.java
Normal file
@ -0,0 +1,43 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
|
||||
/**
|
||||
* @author Kyler Smith, 2017
|
||||
*
|
||||
* Implementation of a character count.
|
||||
* (Slow, could be improved upon, effectively O(n).
|
||||
* */
|
||||
|
||||
public class CountChar {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner input = new Scanner(System.in);
|
||||
System.out.print("Enter your text: ");
|
||||
String str = input.nextLine();
|
||||
|
||||
System.out.println("There are " + CountCharacters(str) + " characters.");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param str: String to count the characters
|
||||
*
|
||||
* @return int: Number of characters in the passed string
|
||||
* */
|
||||
|
||||
public static int CountCharacters(String str) {
|
||||
|
||||
int count = 0;
|
||||
|
||||
if(str == "" || str == null) //Exceptions
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
for(int i = 0; i < str.length(); i++) {
|
||||
if(!Character.isWhitespace(str.charAt(i))) {
|
||||
count++;
|
||||
}}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
56
Misc/Dijkshtra.java
Normal file
56
Misc/Dijkshtra.java
Normal file
@ -0,0 +1,56 @@
|
||||
/*
|
||||
@author : Mayank K Jha
|
||||
|
||||
*/
|
||||
|
||||
|
||||
public class Solution {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
Scanner in =new Scanner(System.in);
|
||||
|
||||
int n=in.nextInt(); //n = Number of nodes or vertices
|
||||
int m=in.nextInt(); //m = Number of Edges
|
||||
long w[][]=new long [n+1][n+1]; //Adjacency Matrix
|
||||
|
||||
//Initializing Matrix with Certain Maximum Value for path b/w any two vertices
|
||||
for (long[] row: w)
|
||||
Arrays.fill(row, 1000000l);
|
||||
//From above,we Have assumed that,initially path b/w any two Pair of vertices is Infinite such that Infinite = 1000000l
|
||||
//For simplicity , We can also take path Value = Long.MAX_VALUE , but i have taken Max Value = 1000000l .
|
||||
|
||||
//Taking Input as Edge Location b/w a pair of vertices
|
||||
for(int i=0;i<m;i++){
|
||||
int x=in.nextInt(),y=in.nextInt();
|
||||
long cmp=in.nextLong();
|
||||
if(w[x][y]>cmp){ //Comparing previous edge value with current value - Cycle Case
|
||||
w[x][y]=cmp; w[y][x]=cmp;
|
||||
}
|
||||
}
|
||||
|
||||
//Implementing Dijkshtra's Algorithm
|
||||
|
||||
Stack <Integer> t=new Stack<Integer>();
|
||||
int src=in.nextInt();
|
||||
for(int i=1;i<=n;i++){
|
||||
if(i!=src){t.push(i);}}
|
||||
Stack <Integer> p=new Stack<Integer>();
|
||||
p.push(src);
|
||||
w[src][src]=0;
|
||||
while(!t.isEmpty()){int min=989997979,loc=-1;
|
||||
for(int i=0;i<t.size();i++){
|
||||
w[src][t.elementAt(i)]=Math.min(w[src][t.elementAt(i)],w[src][p.peek()]
|
||||
+w[p.peek()][t.elementAt(i)]);
|
||||
if(w[src][t.elementAt(i)]<=min){
|
||||
min=(int) w[src][t.elementAt(i)];loc=i;}
|
||||
}
|
||||
p.push(t.elementAt(loc));t.removeElementAt(loc);}
|
||||
|
||||
//Printing shortest path from the given source src
|
||||
for(int i=1;i<=n;i++){
|
||||
if(i!=src && w[src][i]!=1000000l){System.out.print(w[src][i]+" ");}
|
||||
else if(i!=src){System.out.print("-1"+" ");} //Printing -1 if there is no path b/w given pair of edges
|
||||
}
|
||||
|
||||
}
|
||||
}
|
50
Misc/Factorial.java
Normal file
50
Misc/Factorial.java
Normal file
@ -0,0 +1,50 @@
|
||||
package factorial;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* This program will print out the factorial of any non-negative
|
||||
* number that you input into it.
|
||||
*
|
||||
* @author Marcus
|
||||
*
|
||||
*/
|
||||
public class Factorial{
|
||||
|
||||
/**
|
||||
* The main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String[] args){
|
||||
Scanner input = new Scanner(System.in);
|
||||
System.out.print("Enter a non-negative integer: ");
|
||||
|
||||
//If user does not enter an Integer, we want program to fail gracefully, letting the user know why it terminated
|
||||
try{
|
||||
int number = input.nextInt();
|
||||
|
||||
//We keep prompting the user until they enter a positive number
|
||||
while(number < 0){
|
||||
System.out.println("Your input must be non-negative. Please enter a positive number: ");
|
||||
number = input.nextInt();
|
||||
}
|
||||
//Display the result
|
||||
System.out.println("The factorial of " + number + " will yield: " + factorial(number));
|
||||
|
||||
}catch(Exception e){
|
||||
System.out.println("Error: You did not enter an integer. Program has terminated.");
|
||||
}
|
||||
input.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive Factorial Method
|
||||
*
|
||||
* @param n The number to factorial
|
||||
* @return The factorial of the number
|
||||
*/
|
||||
public static long factorial(int n){
|
||||
if(n == 0 || n == 1) return 1;
|
||||
return n * factorial(n - 1);
|
||||
}
|
||||
}
|
45
Misc/FindingPrimes.java
Normal file
45
Misc/FindingPrimes.java
Normal file
@ -0,0 +1,45 @@
|
||||
/**
|
||||
* The Sieve of Eratosthenes is an algorithm use to find prime numbers,
|
||||
* up to a given value.
|
||||
* Illustration: https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
|
||||
* (This illustration is also in the github repository)
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
public class FindingPrimes{
|
||||
/**
|
||||
* The Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]){
|
||||
SOE(20); //Example: Finds all the primes up to 20
|
||||
}
|
||||
|
||||
/**
|
||||
* The method implementing the Sieve of Eratosthenes
|
||||
*
|
||||
* @param n Number to perform SOE on
|
||||
*/
|
||||
public static void SOE(int n){
|
||||
boolean sieve[] = new boolean[n];
|
||||
|
||||
int check = (int)Math.round(Math.sqrt(n)); //No need to check for multiples past the square root of n
|
||||
|
||||
sieve[0] = false;
|
||||
sieve[1] = false;
|
||||
for(int i = 2; i < n; i++)
|
||||
sieve[i] = true; //Set every index to true except index 0 and 1
|
||||
|
||||
for(int i = 2; i< check; i++){
|
||||
if(sieve[i]==true) //If i is a prime
|
||||
for(int j = i+i; j < n; j+=i) //Step through the array in increments of i(the multiples of the prime)
|
||||
sieve[j] = false; //Set every multiple of i to false
|
||||
}
|
||||
for(int i = 0; i< n; i++){
|
||||
if(sieve[i]==true)
|
||||
System.out.print(i+" "); //In this example it will print 2 3 5 7 11 13 17 19
|
||||
}
|
||||
}
|
||||
}
|
144
Misc/LowestBasePalindrome.java
Normal file
144
Misc/LowestBasePalindrome.java
Normal file
@ -0,0 +1,144 @@
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Class for finding the lowest base in which a given integer is a palindrome.
|
||||
* Includes auxiliary methods for converting between bases and reversing strings.
|
||||
*
|
||||
* NOTE: There is potential for error, see note at line 63.
|
||||
*
|
||||
* @author RollandMichael
|
||||
* @version 2017.09.28
|
||||
*
|
||||
*/
|
||||
public class LowestBasePalindrome {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner in = new Scanner(System.in);
|
||||
int n=0;
|
||||
while (true) {
|
||||
try {
|
||||
System.out.print("Enter number: ");
|
||||
n = in.nextInt();
|
||||
break;
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Invalid input!");
|
||||
in.next();
|
||||
}
|
||||
}
|
||||
System.out.println(n+" is a palindrome in base "+lowestBasePalindrome(n));
|
||||
System.out.println(base2base(Integer.toString(n),10, lowestBasePalindrome(n)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a number in base 10, returns the lowest base in which the
|
||||
* number is represented by a palindrome (read the same left-to-right
|
||||
* and right-to-left).
|
||||
* @param num A number in base 10.
|
||||
* @return The lowest base in which num is a palindrome.
|
||||
*/
|
||||
public static int lowestBasePalindrome(int num) {
|
||||
int base, num2=num;
|
||||
int digit;
|
||||
char digitC;
|
||||
boolean foundBase=false;
|
||||
String newNum = "";
|
||||
String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
while (!foundBase) {
|
||||
// Try from bases 2 to num (any number n in base n is 1)
|
||||
for (base=2; base<num2; base++) {
|
||||
newNum="";
|
||||
while(num>0) {
|
||||
// Obtain the first digit of n in the current base,
|
||||
// which is equivalent to the integer remainder of (n/base).
|
||||
// The next digit is obtained by dividing n by the base and
|
||||
// continuing the process of getting the remainder. This is done
|
||||
// until n is <=0 and the number in the new base is obtained.
|
||||
digit = (num % base);
|
||||
num/=base;
|
||||
// If the digit isn't in the set of [0-9][A-Z] (beyond base 36), its character
|
||||
// form is just its value in ASCII.
|
||||
|
||||
// NOTE: This may cause problems, as the capital letters are ASCII values
|
||||
// 65-90. It may cause false positives when one digit is, for instance 10 and assigned
|
||||
// 'A' from the character array and the other is 65 and also assigned 'A'.
|
||||
|
||||
// Regardless, the character is added to the representation of n
|
||||
// in the current base.
|
||||
if (digit>=digits.length()) {
|
||||
digitC=(char)(digit);
|
||||
newNum+=digitC;
|
||||
continue;
|
||||
}
|
||||
newNum+=digits.charAt(digit);
|
||||
}
|
||||
// Num is assigned back its original value for the next iteration.
|
||||
num=num2;
|
||||
// Auxiliary method reverses the number.
|
||||
String reverse = reverse(newNum);
|
||||
// If the number is read the same as its reverse, then it is a palindrome.
|
||||
// The current base is returned.
|
||||
if (reverse.equals(newNum)) {
|
||||
foundBase=true;
|
||||
return base;
|
||||
}
|
||||
}
|
||||
}
|
||||
// If all else fails, n is always a palindrome in base n-1. ("11")
|
||||
return num-1;
|
||||
}
|
||||
|
||||
private static String reverse(String str) {
|
||||
String reverse = "";
|
||||
for(int i=str.length()-1; i>=0; i--) {
|
||||
reverse += str.charAt(i);
|
||||
}
|
||||
return reverse;
|
||||
}
|
||||
|
||||
private static String base2base(String n, int b1, int b2) {
|
||||
// Declare variables: decimal value of n,
|
||||
// character of base b1, character of base b2,
|
||||
// and the string that will be returned.
|
||||
int decimalValue = 0, charB2;
|
||||
char charB1;
|
||||
String output="";
|
||||
// Go through every character of n
|
||||
for (int i=0; i<n.length(); i++) {
|
||||
// store the character in charB1
|
||||
charB1 = n.charAt(i);
|
||||
// if it is a non-number, convert it to a decimal value >9 and store it in charB2
|
||||
if (charB1 >= 'A' && charB1 <= 'Z')
|
||||
charB2 = 10 + (charB1 - 'A');
|
||||
// Else, store the integer value in charB2
|
||||
else
|
||||
charB2 = charB1 - '0';
|
||||
// Convert the digit to decimal and add it to the
|
||||
// decimalValue of n
|
||||
decimalValue = decimalValue * b1 + charB2;
|
||||
}
|
||||
|
||||
// Converting the decimal value to base b2:
|
||||
// A number is converted from decimal to another base
|
||||
// by continuously dividing by the base and recording
|
||||
// the remainder until the quotient is zero. The number in the
|
||||
// new base is the remainders, with the last remainder
|
||||
// being the left-most digit.
|
||||
|
||||
// While the quotient is NOT zero:
|
||||
while (decimalValue != 0) {
|
||||
// If the remainder is a digit < 10, simply add it to
|
||||
// the left side of the new number.
|
||||
if (decimalValue % b2 < 10)
|
||||
output = Integer.toString(decimalValue % b2) + output;
|
||||
// If the remainder is >= 10, add a character with the
|
||||
// corresponding value to the new number. (A = 10, B = 11, C = 12, ...)
|
||||
else
|
||||
output = (char)((decimalValue % b2)+55) + output;
|
||||
// Divide by the new base again
|
||||
decimalValue /= b2;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
}
|
16
Misc/Node.java
Normal file
16
Misc/Node.java
Normal file
@ -0,0 +1,16 @@
|
||||
public class Node {
|
||||
public Object anElement;
|
||||
public Node less;
|
||||
public Node greater;
|
||||
|
||||
public Node(Object theElement) {
|
||||
this(theElement, null, null); //an empty node at the end will be by itself with no children, therefore the other 2 parameters are always null
|
||||
//obviously the node can still be a child of other elements
|
||||
}
|
||||
|
||||
public Node(Object currentElement, Node lessSide, Node greaterSide) {
|
||||
anElement = currentElement;
|
||||
this.less = lessSide;
|
||||
this.greater = greaterSide;
|
||||
}
|
||||
}
|
16
Misc/Palindrome.java
Normal file
16
Misc/Palindrome.java
Normal file
@ -0,0 +1,16 @@
|
||||
class Palindrome {
|
||||
|
||||
public String reverseString(String x){ //*helper method
|
||||
String output = "";
|
||||
for(int i=x.length()-1; i>=0; i--){
|
||||
output += x.charAt(i); //addition of chars create String
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
public Boolean isPalindrome(String x){ //*palindrome method, returns true if palindrome
|
||||
return (x.equalsIgnoreCase(reverseString(x)));
|
||||
}
|
||||
|
||||
}
|
46
Misc/ReverseString.java
Normal file
46
Misc/ReverseString.java
Normal file
@ -0,0 +1,46 @@
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
/**
|
||||
* This method produces a reversed version of a string
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class ReverseString
|
||||
{
|
||||
|
||||
/**
|
||||
* This method reverses the string str and returns it
|
||||
* @param str String to be reversed
|
||||
* @return Reversed string
|
||||
*/
|
||||
public static String reverse(String str){
|
||||
if(str.isEmpty() || str == null) return str;
|
||||
|
||||
char arr[] = str.toCharArray();
|
||||
for(int i = 0, j = str.length() - 1; i < j; i++, j--){
|
||||
char temp = arr[i];
|
||||
arr[i] = arr[j];
|
||||
arr[j] = temp;
|
||||
}
|
||||
return new String(arr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main Method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
* @throws IOException Exception thrown because of BufferedReader
|
||||
*/
|
||||
public static void main(String args[]) throws IOException
|
||||
{
|
||||
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
|
||||
System.out.println("Enter the string");
|
||||
String srr=br.readLine();
|
||||
System.out.println("Reverse="+reverseString(srr));
|
||||
br.close();
|
||||
}
|
||||
}
|
||||
|
26
Misc/countwords.java
Normal file
26
Misc/countwords.java
Normal file
@ -0,0 +1,26 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* You enter a string into this program, and it will return how
|
||||
* many words were in that particular string
|
||||
*
|
||||
* @author Marcus
|
||||
*
|
||||
*/
|
||||
class CountTheWords{
|
||||
|
||||
public static void main(String[] args){
|
||||
Scanner input = new Scanner(System.in);
|
||||
System.out.println("Enter your text: ");
|
||||
String str = input.nextLine();
|
||||
|
||||
System.out.println("Your text has " + wordCount(str) + " word(s)");
|
||||
input.close();
|
||||
}
|
||||
|
||||
public static int wordCount(String s){
|
||||
if(s.isEmpty() || s == null) return -1;
|
||||
return s.trim().split("[\\s]+").length;
|
||||
}
|
||||
|
||||
}
|
17
Misc/ft.java
Normal file
17
Misc/ft.java
Normal file
@ -0,0 +1,17 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
|
||||
class FloydTriangle {
|
||||
public static void main(String[] args) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.println("Enter the number of rows which you want in your Floyd Triangle: ");
|
||||
int r = sc.nextInt(), n = 0;
|
||||
|
||||
for(int i=0; i < r; i++) {
|
||||
for(int j=0; j <= i; j++) {
|
||||
System.out.print(++n + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
}
|
29
Misc/krishnamurthy.java
Normal file
29
Misc/krishnamurthy.java
Normal file
@ -0,0 +1,29 @@
|
||||
import java.util.Scanner;
|
||||
class krishnamurthy
|
||||
{
|
||||
int fact(int n)
|
||||
{
|
||||
int i,p=1;
|
||||
for(i=n;i>=1;i--)
|
||||
p=p*i;
|
||||
return p;
|
||||
}
|
||||
public static void main(String args[])
|
||||
{
|
||||
Scanner sc=new Scanner(System.in);
|
||||
int a,b,s=0;
|
||||
System.out.print("Enter the number : ");
|
||||
a=sc.nextInt();
|
||||
int n=a;
|
||||
while(a>0)
|
||||
{
|
||||
b=a%10;
|
||||
s=s+fact(b);
|
||||
a=a/10;
|
||||
}
|
||||
if(s==n)
|
||||
System.out.print(n+" is a krishnamurthy number");
|
||||
else
|
||||
System.out.print(n+" is not a krishnamurthy number");
|
||||
}
|
||||
}
|
45
Misc/removeDuplicateFromString.java
Normal file
45
Misc/removeDuplicateFromString.java
Normal file
@ -0,0 +1,45 @@
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
public class removeDuplicateFromString {
|
||||
public static void main (String[] args) throws Exception{
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||
String inp_str = br.readLine();
|
||||
|
||||
System.out.println("Actual string is: " + inp_str);
|
||||
System.out.println("String after removing duplicates: " + removeDuplicate(inp_str));
|
||||
|
||||
br.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method produces a string after removing all the duplicate characters from input string and returns it
|
||||
* Example: Input String - "aabbbccccddddd"
|
||||
* Output String - "abcd"
|
||||
* @param s String from which duplicate characters have to be removed
|
||||
* @return string with only unique characters
|
||||
*/
|
||||
|
||||
public static String removeDuplicate(String s) {
|
||||
if(s.isEmpty() || s == null) {
|
||||
return s;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder("");
|
||||
int n = s.length();
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (sb.toString().indexOf(s.charAt(i)) == -1) {
|
||||
sb.append(String.valueOf(s.charAt(i)));
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
99
README.md
99
README.md
@ -1,2 +1,97 @@
|
||||
# Java
|
||||
All Algorithms implemented in Java
|
||||
# The Algorithms - Java [![Build Status](https://travis-ci.org/TheAlgorithms/Python.svg)](https://travis-ci.org/TheAlgorithms/Python)
|
||||
|
||||
### All algorithms implemented in Java (for education)
|
||||
|
||||
These are for demonstration purposes only. There are many implementations of sorts in the Java standard library that are much better for performance reasons.
|
||||
|
||||
## Sort Algorithms
|
||||
|
||||
|
||||
### Bubble
|
||||
![alt text][bubble-image]
|
||||
|
||||
From [Wikipedia][bubble-wiki]: Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
|
||||
|
||||
__Properties__
|
||||
* Worst case performance O(n^2)
|
||||
* Best case performance O(n)
|
||||
* Average case performance O(n^2)
|
||||
|
||||
###### View the algorithm in [action][bubble-toptal]
|
||||
|
||||
|
||||
|
||||
### Insertion
|
||||
![alt text][insertion-image]
|
||||
|
||||
From [Wikipedia][insertion-wiki]: Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
|
||||
|
||||
__Properties__
|
||||
* Worst case performance O(n^2)
|
||||
* Best case performance O(n)
|
||||
* Average case performance O(n^2)
|
||||
|
||||
###### View the algorithm in [action][insertion-toptal]
|
||||
|
||||
|
||||
### Merge
|
||||
![alt text][merge-image]
|
||||
|
||||
From [Wikipedia][merge-wiki]: In computer science, merge sort (also commonly spelled mergesort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945.
|
||||
|
||||
__Properties__
|
||||
* Worst case performance O(n log n)
|
||||
* Best case performance O(n)
|
||||
* Average case performance O(n)
|
||||
|
||||
|
||||
###### View the algorithm in [action][merge-toptal]
|
||||
|
||||
|
||||
|
||||
### Selection
|
||||
![alt text][selection-image]
|
||||
|
||||
From [Wikipedia][selection-wiki]: The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.
|
||||
|
||||
__Properties__
|
||||
* Worst case performance O(n^2)
|
||||
* Best case performance O(n^2)
|
||||
* Average case performance O(n^2)
|
||||
|
||||
###### View the algorithm in [action][selection-toptal]
|
||||
|
||||
|
||||
|
||||
[bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort
|
||||
[bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort
|
||||
[bubble-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Bubblesort-edited-color.svg/220px-Bubblesort-edited-color.svg.png "Bubble Sort"
|
||||
|
||||
[insertion-toptal]: https://www.toptal.com/developers/sorting-algorithms/insertion-sort
|
||||
[insertion-wiki]: https://en.wikipedia.org/wiki/Insertion_sort
|
||||
[insertion-image]: https://upload.wikimedia.org/wikipedia/commons/7/7e/Insertionsort-edited.png "Insertion Sort"
|
||||
|
||||
[quick-toptal]: https://www.toptal.com/developers/sorting-algorithms/quick-sort
|
||||
[quick-wiki]: https://en.wikipedia.org/wiki/Quicksort
|
||||
[quick-image]: https://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif "Quick Sort"
|
||||
|
||||
[merge-toptal]: https://www.toptal.com/developers/sorting-algorithms/merge-sort
|
||||
[merge-wiki]: https://en.wikipedia.org/wiki/Merge_sort
|
||||
[merge-image]: https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif "Merge Sort"
|
||||
|
||||
[selection-toptal]: https://www.toptal.com/developers/sorting-algorithms/selection-sort
|
||||
[selection-wiki]: https://en.wikipedia.org/wiki/Selection_sort
|
||||
[selection-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/Selection_sort_animation.gif/250px-Selection_sort_animation.gif "Selection Sort Sort"
|
||||
|
||||
[shell-toptal]: https://www.toptal.com/developers/sorting-algorithms/shell-sort
|
||||
[shell-wiki]: https://en.wikipedia.org/wiki/Shellsort
|
||||
[shell-image]: https://upload.wikimedia.org/wikipedia/commons/d/d8/Sorting_shellsort_anim.gif "Shell Sort"
|
||||
|
||||
[linear-wiki]: https://en.wikipedia.org/wiki/Linear_search
|
||||
[linear-image]: http://www.tutorialspoint.com/data_structures_algorithms/images/linear_search.gif
|
||||
|
||||
[binary-wiki]: https://en.wikipedia.org/wiki/Binary_search_algorithm
|
||||
[binary-image]: https://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_search_into_array.png
|
||||
|
||||
|
||||
[caesar]: https://upload.wikimedia.org/wikipedia/commons/4/4a/Caesar_cipher_left_shift_of_3.svg
|
||||
|
71
Searches/BinarySearch.java
Normal file
71
Searches/BinarySearch.java
Normal file
@ -0,0 +1,71 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
class BinarySearch
|
||||
{
|
||||
/**
|
||||
* This method implements the Generic Binary Search
|
||||
*
|
||||
* @param array The array to make the binary search
|
||||
* @param key The number you are looking for
|
||||
* @param lb The lower bound
|
||||
* @param ub The upper bound
|
||||
* @return the location of the key
|
||||
**/
|
||||
|
||||
public static <T extends Comparable<T>> int BS(T array[], T key, int lb, int ub)
|
||||
{
|
||||
if ( lb > ub)
|
||||
return -1;
|
||||
|
||||
int mid = (ub+lb)/2;
|
||||
int comp = key.compareTo(array[mid]);
|
||||
|
||||
if (comp < 0)
|
||||
return (BS(array, key, lb, mid-1));
|
||||
|
||||
if (comp > 0)
|
||||
return (BS(array, key, mid + 1, ub));
|
||||
|
||||
return mid;
|
||||
}
|
||||
|
||||
// Driver Program
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner input=new Scanner(System.in);
|
||||
|
||||
// For INTEGER Input
|
||||
Integer[] array = new Integer[10];
|
||||
int key = 5;
|
||||
|
||||
for (int i = 0; i < 10 ; i++ )
|
||||
array[i] = i+1;
|
||||
|
||||
int index = BS(array, key, 0, 9);
|
||||
|
||||
if (index != -1)
|
||||
System.out.println("Number " + key + " found at index number : " + index);
|
||||
else
|
||||
System.out.println("Not found");
|
||||
|
||||
|
||||
// For STRING Input
|
||||
String[] array1 = {"a", "b", "c", "d", "e"};
|
||||
String key1 = "d";
|
||||
|
||||
int index1 = BS(array1, key1, 0, array1.length-1);
|
||||
|
||||
if (index1 != -1)
|
||||
System.out.println("String " + key1 + " found at index number : " + index1);
|
||||
else
|
||||
System.out.println("Not found");
|
||||
|
||||
input.close();
|
||||
}
|
||||
}
|
77
Searches/LinearSearch.java
Normal file
77
Searches/LinearSearch.java
Normal file
@ -0,0 +1,77 @@
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
public class LinearSearch{
|
||||
/**
|
||||
* The main method
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||
|
||||
// Test for Integer inputs
|
||||
Integer[] myArray;
|
||||
int size = 0;
|
||||
|
||||
//Prompt user to create array and its elements
|
||||
System.out.print("Enter the array size: ");
|
||||
size = Integer.parseInt(br.readLine());
|
||||
myArray = new Integer[size];
|
||||
for (int i = 0; i < size; i++){
|
||||
System.out.print("For index " + i + ", enter an integer: ");
|
||||
myArray[i] = Integer.parseInt(br.readLine());
|
||||
}
|
||||
|
||||
//Prompt user to search for particular element
|
||||
System.out.print("Enter integer to search for: ");
|
||||
Integer key = Integer.parseInt(br.readLine());
|
||||
|
||||
//Output array and index of target element, if found
|
||||
System.out.printf("The integer %d is found in index %d\n", key, linearSearch(myArray, key));
|
||||
|
||||
// Test for String inputs
|
||||
String[] myArray1;
|
||||
int size1 = 0;
|
||||
|
||||
//Prompt user to create array and its elements
|
||||
System.out.print("Enter the array size: ");
|
||||
size1 = Integer.parseInt(br.readLine());
|
||||
myArray1 = new String[size];
|
||||
for (int i = 0; i < size1; i++){
|
||||
System.out.print("For index " + i + ", enter a String: ");
|
||||
myArray1[i] = br.readLine();
|
||||
}
|
||||
|
||||
//Prompt user to search for particular element
|
||||
System.out.print("Enter String to search for: ");
|
||||
String key1 = br.readLine();
|
||||
|
||||
//Output array and index of target element, if found
|
||||
System.out.printf("The string %s is found in index %d\n", key1, linearSearch(myArray1, key1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic Linear search method
|
||||
*
|
||||
* @param array List to be searched
|
||||
* @param value Key being searched for
|
||||
* @return Location of the key
|
||||
*/
|
||||
public static <T extends Comparable<T>> int linearSearch(T[] array, T value) {
|
||||
int lo = 0;
|
||||
int hi = array.length - 1;
|
||||
for (int i = lo; i <= hi; i++) {
|
||||
if (array[i].compareTo(value) == 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
class SelectionSort
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
int array[]=new int[6];
|
||||
Scanner input=new Scanner(System.in);
|
||||
|
||||
//Input
|
||||
System.out.println("Enter any 6 Numbers for Unsorted Array : ");
|
||||
for(int i=0; i<6; i++)
|
||||
{
|
||||
array[i]=input.nextInt();
|
||||
}
|
||||
|
||||
//Sorting
|
||||
for(int i=0; i<6; i++)
|
||||
{
|
||||
int min=i;
|
||||
for(int j=i+1; j<6; j++)
|
||||
{
|
||||
if(array[j]<array[min])
|
||||
{
|
||||
min=j;
|
||||
}
|
||||
}
|
||||
int temp=array[i];
|
||||
array[i]=array[min];
|
||||
array[min]=temp;
|
||||
}
|
||||
|
||||
//Output
|
||||
for(int i=0; i<6; i++)
|
||||
{
|
||||
System.out.print(array[i]+"\t");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
80
Sorts/BinaryTreeSort.java
Normal file
80
Sorts/BinaryTreeSort.java
Normal file
@ -0,0 +1,80 @@
|
||||
import java.util.Arrays;
|
||||
public class TreeSort {
|
||||
|
||||
public Node root;
|
||||
|
||||
public TreeSort(Object x) {
|
||||
root = new Node(x);
|
||||
}//end TreeSort constructor
|
||||
|
||||
public Node insert(Node node, Integer x) {
|
||||
if (node == null) {
|
||||
return node = new Node(x);
|
||||
}//end if
|
||||
if (x < (Integer) node.anElement) {
|
||||
node.less = insert(node.less, x);
|
||||
} //end if
|
||||
else {
|
||||
node.greater = insert(node.greater, x);
|
||||
}//end else
|
||||
return node;
|
||||
}//end insert
|
||||
|
||||
|
||||
public Node decimalInsert(Node node, Double x) {
|
||||
if (node == null) {
|
||||
return node = new Node(x);
|
||||
}//end if
|
||||
if (x < (Double) node.anElement) {
|
||||
node.less = decimalInsert(node.less, x);
|
||||
} //end if
|
||||
else {
|
||||
node.greater = decimalInsert(node.greater, x);
|
||||
}//end else
|
||||
return node;
|
||||
}//end insert
|
||||
|
||||
|
||||
public void treeSort(Node node) {
|
||||
if (node != null) {
|
||||
treeSort(node.less);
|
||||
System.out.print(((Object) node.anElement) + ", ");
|
||||
treeSort(node.greater);
|
||||
}//end if
|
||||
}//end TreeSort class
|
||||
|
||||
|
||||
|
||||
public static void main(String args[]) {
|
||||
int[] intArray = {12, 40, 9, 3, 19, 74, 7, 31, 23, 54, 26, 81, 12 };
|
||||
TreeSort ts = new TreeSort(new Integer(intArray[0]));
|
||||
for (int i = 1; i < intArray.length; i++) { //sorts every index of the list one at a time
|
||||
ts.insert(ts.root, new Integer(intArray[i])); //builds on the tree from a root node
|
||||
}//end for
|
||||
System.out.print("Integer Array Sorted in Increasing Order: ");
|
||||
ts.treeSort(ts.root);
|
||||
System.out.println(); //To sort a test array of integers
|
||||
|
||||
Double[] decimalArray = {8.2, 1.5, 3.14159265, 9.3, 5.1, 4.8, 2.6};
|
||||
TreeSort dts = new TreeSort(new Double(decimalArray[0]).doubleValue());
|
||||
for (int i = 1; i < decimalArray.length; i++) { //sorts every index of the list one at a time
|
||||
dts.decimalInsert(dts.root, new Double(decimalArray[i]).doubleValue()); //builds on the tree from a root node
|
||||
}//end for
|
||||
System.out.print("Decimal Array, Sorted in Increasing Order: ");
|
||||
dts.treeSort(dts.root);
|
||||
System.out.println();
|
||||
|
||||
String[] stringArray = {"c", "a", "e", "b","d", "dd","da","zz", "AA", "aa","aB","Hb", "Z"};
|
||||
int last = stringArray.length;
|
||||
Arrays.sort(stringArray); //Uses an imported arrays method to automatically alphabetize
|
||||
System.out.print("String Array Sorted in Alphabetical Order: ");
|
||||
ts.insert(ts.root, last);
|
||||
for(int i=0; i<last; i++){
|
||||
System.out.print(stringArray[i]+"\t");
|
||||
//To sort a test array of strings hard coded in the main method
|
||||
//Please Note that Capital letters always come before lower case
|
||||
//I tried to make the test array show its behavior clearly
|
||||
}//end for
|
||||
}//end Main method
|
||||
}//end TreeSort class
|
||||
|
70
Sorts/BubbleSort.java
Normal file
70
Sorts/BubbleSort.java
Normal file
@ -0,0 +1,70 @@
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
class BubbleSort
|
||||
{
|
||||
/**
|
||||
* This method implements the Generic Bubble Sort
|
||||
*
|
||||
* @param array The array to be sorted
|
||||
* @param last The count of total number of elements in array
|
||||
* Sorts the array in increasing order
|
||||
**/
|
||||
|
||||
public static <T extends Comparable<T>> void BS(T array[], int last) {
|
||||
//Sorting
|
||||
boolean swap;
|
||||
do
|
||||
{
|
||||
swap = false;
|
||||
for (int count = 0; count < last-1; count++)
|
||||
{
|
||||
int comp = array[count].compareTo(array[count + 1]);
|
||||
if (comp > 0)
|
||||
{
|
||||
T temp = array[count];
|
||||
array[count] = array[count + 1];
|
||||
array[count + 1] = temp;
|
||||
swap = true;
|
||||
}
|
||||
}
|
||||
last--;
|
||||
} while (swap);
|
||||
}
|
||||
|
||||
// Driver Program
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// Integer Input
|
||||
int[] arr1 = {4,23,6,78,1,54,231,9,12};
|
||||
int last = arr1.length;
|
||||
Integer[] array = new Integer[last];
|
||||
for (int i=0;i<last;i++) {
|
||||
array[i] = arr1[i];
|
||||
}
|
||||
|
||||
BS(array, last);
|
||||
|
||||
// Output => 1 4 6 9 12 23 54 78 231
|
||||
for(int i=0; i<last; i++)
|
||||
{
|
||||
System.out.print(array[i]+"\t");
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
// String Input
|
||||
String[] array1 = {"c", "a", "e", "b","d"};
|
||||
last = array1.length;
|
||||
|
||||
BS(array1, last);
|
||||
|
||||
//Output => a b c d e
|
||||
for(int i=0; i<last; i++)
|
||||
{
|
||||
System.out.print(array1[i]+"\t");
|
||||
}
|
||||
}
|
||||
}
|
174
Sorts/HeapSort.java
Normal file
174
Sorts/HeapSort.java
Normal file
@ -0,0 +1,174 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Heap Sort Algorithm
|
||||
* Implements MinHeap
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
public class HeapSort {
|
||||
/** Array to store heap */
|
||||
private int[] heap;
|
||||
/** The size of the heap */
|
||||
private int size;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param heap array of unordered integers
|
||||
*/
|
||||
public HeapSort(int[] heap) {
|
||||
this.setHeap(heap);
|
||||
this.setSize(heap.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Setter for variable size
|
||||
*
|
||||
* @param length new size
|
||||
*/
|
||||
private void setSize(int length) {
|
||||
this.size = length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setter for variable heap
|
||||
*
|
||||
* @param heap array of unordered elements
|
||||
*/
|
||||
private void setHeap(int[] heap) {
|
||||
this.heap = heap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Swaps index of first with second
|
||||
*
|
||||
* @param first First index to switch
|
||||
* @param second Second index to switch
|
||||
*/
|
||||
private void swap(int first, int second) {
|
||||
int temp = this.heap[first];
|
||||
this.heap[first] = this.heap[second];
|
||||
this.heap[second] = temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Heapifies subtree from top as root to last as last child
|
||||
*
|
||||
* @param rootIndex index of root
|
||||
* @param lastChild index of last child
|
||||
*/
|
||||
private void heapSubtree(int rootIndex, int lastChild) {
|
||||
int leftIndex = rootIndex * 2 + 1;
|
||||
int rightIndex = rootIndex * 2 + 2;
|
||||
int root = this.heap[rootIndex];
|
||||
if (rightIndex <= lastChild) { // if has right and left children
|
||||
int left = this.heap[leftIndex];
|
||||
int right = this.heap[rightIndex];
|
||||
if (left < right && left < root) {
|
||||
this.swap(leftIndex, rootIndex);
|
||||
this.heapSubtree(leftIndex, lastChild);
|
||||
} else if (right < root) {
|
||||
this.swap(rightIndex, rootIndex);
|
||||
this.heapSubtree(rightIndex, lastChild);
|
||||
}
|
||||
} else if (leftIndex <= lastChild) { // if no right child, but has left child
|
||||
int left = this.heap[leftIndex];
|
||||
if (left < root) {
|
||||
this.swap(leftIndex, rootIndex);
|
||||
this.heapSubtree(leftIndex, lastChild);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes heap with root as root
|
||||
*
|
||||
* @param root index of root of heap
|
||||
*/
|
||||
private void makeMinHeap(int root) {
|
||||
int leftIndex = root * 2 + 1;
|
||||
int rightIndex = root * 2 + 2;
|
||||
boolean hasLeftChild = leftIndex < this.heap.length;
|
||||
boolean hasRightChild = rightIndex < this.heap.length;
|
||||
if (hasRightChild) { //if has left and right
|
||||
this.makeMinHeap(leftIndex);
|
||||
this.makeMinHeap(rightIndex);
|
||||
this.heapSubtree(root, this.heap.length - 1);
|
||||
} else if (hasLeftChild) {
|
||||
this.heapSubtree(root, this.heap.length - 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the root of heap
|
||||
*
|
||||
* @return root of heap
|
||||
*/
|
||||
private int getRoot() {
|
||||
this.swap(0, this.size - 1);
|
||||
this.size--;
|
||||
this.heapSubtree(0, this.size - 1);
|
||||
return this.heap[this.size]; // return old root
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts heap with heap sort; displays ordered elements to console.
|
||||
*
|
||||
* @return sorted array of sorted elements
|
||||
*/
|
||||
public final int[] sort() {
|
||||
this.makeMinHeap(0); // make min heap using index 0 as root.
|
||||
int[] sorted = new int[this.size];
|
||||
int index = 0;
|
||||
while (this.size > 0) {
|
||||
int min = this.getRoot();
|
||||
sorted[index] = min;
|
||||
index++;
|
||||
}
|
||||
return sorted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets input to sort
|
||||
*
|
||||
* @return unsorted array of integers to sort
|
||||
*/
|
||||
public static int[] getInput() {
|
||||
final int numElements = 6;
|
||||
int[] unsorted = new int[numElements];
|
||||
Scanner input = new Scanner(System.in);
|
||||
System.out.println("Enter any 6 Numbers for Unsorted Array : ");
|
||||
for (int i = 0; i < numElements; i++) {
|
||||
unsorted[i] = input.nextInt();
|
||||
}
|
||||
input.close();
|
||||
return unsorted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints elements in heap
|
||||
*
|
||||
* @param heap array representing heap
|
||||
*/
|
||||
public static void printData(int[] heap) {
|
||||
System.out.println("Sorted Elements:");
|
||||
for (int i = 0; i < heap.length; i++) {
|
||||
System.out.print(" " + heap[i] + " ");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args the command line arguments
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
int[] heap = getInput();
|
||||
HeapSort data = new HeapSort(heap);
|
||||
int[] sorted = data.sort();
|
||||
printData(sorted);
|
||||
}
|
||||
|
||||
}
|
63
Sorts/InsertionSort.java
Normal file
63
Sorts/InsertionSort.java
Normal file
@ -0,0 +1,63 @@
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
class InsertionSort {
|
||||
|
||||
/**
|
||||
* This method implements the Generic Insertion Sort
|
||||
*
|
||||
* @param array The array to be sorted
|
||||
* @param last The count of total number of elements in array
|
||||
* Sorts the array in increasing order
|
||||
**/
|
||||
|
||||
public static <T extends Comparable<T>> void IS(T array[], int last) {
|
||||
T key;
|
||||
for (int j=1;j<last;j++) {
|
||||
|
||||
// Picking up the key(Card)
|
||||
key = array[j];
|
||||
int i = j-1;
|
||||
while (i>=0 && key.compareTo(array[i]) < 0) {
|
||||
array[i+1] = array[i];
|
||||
i--;
|
||||
}
|
||||
// Placing the key (Card) at its correct position in the sorted subarray
|
||||
array[i+1] = key;
|
||||
}
|
||||
}
|
||||
|
||||
// Driver Program
|
||||
public static void main(String[] args) {
|
||||
// Integer Input
|
||||
int[] arr1 = {4,23,6,78,1,54,231,9,12};
|
||||
int last = arr1.length;
|
||||
Integer[] array = new Integer[arr1.length];
|
||||
for (int i=0;i<arr1.length;i++) {
|
||||
array[i] = arr1[i];
|
||||
}
|
||||
|
||||
IS(array, last);
|
||||
|
||||
// Output => 1 4 6 9 12 23 54 78 231
|
||||
for (int i=0;i<array.length;i++) {
|
||||
System.out.print(array[i] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
// String Input
|
||||
String[] array1 = {"c", "a", "e", "b","d"};
|
||||
last = array1.length;
|
||||
|
||||
IS(array1, last);
|
||||
|
||||
//Output => a b c d e
|
||||
for(int i=0; i<last; i++)
|
||||
{
|
||||
System.out.print(array1[i]+"\t");
|
||||
}
|
||||
}
|
||||
}
|
61
Sorts/InsertionSortInteger.java
Normal file
61
Sorts/InsertionSortInteger.java
Normal file
@ -0,0 +1,61 @@
|
||||
/**
|
||||
* This is my implementation of an insertion sort.
|
||||
*
|
||||
* I decided to do this when i didn't feel comfortable enough about implementing
|
||||
* different types of sorts, so this is my trial and error to try and get myself to implement
|
||||
* the various sorts correctly.
|
||||
*
|
||||
* @author Kody C. Kendall
|
||||
*
|
||||
*/
|
||||
public class InsertionSortInteger {
|
||||
|
||||
|
||||
/**
|
||||
* This method implements insertion sort by integer
|
||||
*
|
||||
* @param initialArray array to be sorted
|
||||
* @return sorted array
|
||||
*/
|
||||
public int[] insertionIntArraySort(int[] initialArray){
|
||||
|
||||
int[] sortedArray = new int[initialArray.length];
|
||||
|
||||
//Marking first element as sorted.
|
||||
sortedArray[0] = initialArray[0];
|
||||
|
||||
//For each element in the initialArray
|
||||
for (int index = 1; index < initialArray.length; index++){
|
||||
|
||||
//Finding the last index that was sorted
|
||||
int lastSortedIndex = index;
|
||||
|
||||
//Extracting the next element to be compared w/ other sorted elements from initial array
|
||||
int extractedElement = initialArray[index];
|
||||
|
||||
//Compare the values of the sorted index to the current extractedElement
|
||||
for (lastSortedIndex = index; lastSortedIndex > 0; lastSortedIndex--){
|
||||
|
||||
//If our extracted element is smaller than element to the right, switch them.
|
||||
if (sortedArray[lastSortedIndex-1] > extractedElement){
|
||||
//move the element to the left of extractedElement to the right in sortedArray
|
||||
sortedArray[lastSortedIndex] = sortedArray[lastSortedIndex-1];
|
||||
//And move the current extractedElement to the left one (since it's smaller).
|
||||
sortedArray[lastSortedIndex-1] = extractedElement;
|
||||
}
|
||||
else{
|
||||
//insert element where it is.
|
||||
sortedArray[lastSortedIndex] = extractedElement;
|
||||
//Terminating loop since element is in the right spot.
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return sortedArray;
|
||||
|
||||
}
|
||||
|
||||
}
|
100
Sorts/MergeSort.java
Normal file
100
Sorts/MergeSort.java
Normal file
@ -0,0 +1,100 @@
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
class MergeSort {
|
||||
|
||||
/**
|
||||
* This method implements the Generic Merge Sort
|
||||
*
|
||||
* @param arr The array to be sorted
|
||||
* @param temp The copy of the actual array
|
||||
* @param left The first index of the array
|
||||
* @param right The last index of the array
|
||||
* Recursively sorts the array in increasing order
|
||||
**/
|
||||
|
||||
public static <T extends Comparable<T>> void MS(T[] arr, T[] temp, int left, int right) {
|
||||
if (left < right) {
|
||||
int mid = left + (right - left) / 2;
|
||||
MS(arr, temp, left, mid);
|
||||
MS(arr, temp,mid + 1, right);
|
||||
merge(arr, temp, left, mid, right);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* This method implements the merge step of the merge sort
|
||||
*
|
||||
* @param arr The array to be sorted
|
||||
* @param temp The copy of the actual array
|
||||
* @param left The first index of the array
|
||||
* @param mid The middle index of the array
|
||||
* @param right The last index of the array
|
||||
* merges two parts of an array in increasing order
|
||||
**/
|
||||
|
||||
public static <T extends Comparable<T>> void merge(T[] arr, T[] temp, int left, int mid, int right) {
|
||||
for (int i=left;i<=right;i++) {
|
||||
temp[i] = arr[i];
|
||||
}
|
||||
|
||||
int i= left;
|
||||
int j = mid + 1;
|
||||
int k = left;
|
||||
|
||||
while (i<=mid && j<=right) {
|
||||
if (temp[i].compareTo(temp[j]) <= 0) {
|
||||
arr[k] = temp[i];
|
||||
i++;
|
||||
}
|
||||
else {
|
||||
arr[k] = temp[j];
|
||||
j++;
|
||||
}
|
||||
k++;
|
||||
}
|
||||
|
||||
while (i <= mid) {
|
||||
arr[k] = temp[i];
|
||||
i++;
|
||||
k++;
|
||||
}
|
||||
}
|
||||
|
||||
// Driver program
|
||||
public static void main(String[] args) {
|
||||
|
||||
// Integer Input
|
||||
int[] arr = {4,23,6,78,1,54,231,9,12};
|
||||
Integer[] array = new Integer[arr.length];
|
||||
for (int i=0;i<array.length;i++) {
|
||||
array[i] = arr[i];
|
||||
}
|
||||
|
||||
// Copy of actual array
|
||||
Integer[] temp = new Integer[arr.length];
|
||||
|
||||
MS(array, temp, 0, arr.length-1);
|
||||
|
||||
// Output => 1 4 6 9 12 23 54 78 231
|
||||
for (int i=0;i<arr.length;i++) {
|
||||
System.out.print(array[i] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
// String Input
|
||||
String[] array1 = {"c", "a", "e", "b","d"};
|
||||
String[] temp1 = new String[array1.length];
|
||||
MS(array1, temp1, 0, array1.length-1);
|
||||
|
||||
//Output => a b c d e
|
||||
for(int i=0; i<array1.length; i++)
|
||||
{
|
||||
System.out.print(array1[i]+"\t");
|
||||
}
|
||||
}
|
||||
}
|
93
Sorts/QuickSort.java
Normal file
93
Sorts/QuickSort.java
Normal file
@ -0,0 +1,93 @@
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
class QuickSort {
|
||||
|
||||
/**
|
||||
* This method implements the Generic Quick Sort
|
||||
*
|
||||
* @param array The array to be sorted
|
||||
* @param start The first index of an array
|
||||
* @param end The last index of an array
|
||||
* Sorts the array in increasing order
|
||||
**/
|
||||
|
||||
public static <T extends Comparable<T>> void QS(T array[], int start, int end) {
|
||||
if (start < end) {
|
||||
int PIndex = partition(array, start, end);
|
||||
QS(array, start, PIndex - 1);
|
||||
QS(array, PIndex + 1, end);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method finds the partition index for an array
|
||||
*
|
||||
* @param array The array to be sorted
|
||||
* @param start The first index of an array
|
||||
* @param end The last index of an array
|
||||
* Finds the partition index of an array
|
||||
**/
|
||||
|
||||
public static <T extends Comparable<T>> int partition(T array[], int start, int end) {
|
||||
T pivot = array[end];
|
||||
int PIndex = start;
|
||||
for (int i=start;i<end;i++) {
|
||||
if (array[i].compareTo(pivot) <= 0) {
|
||||
swap(array, i, PIndex);
|
||||
PIndex++;
|
||||
}
|
||||
}
|
||||
swap(array, PIndex, end);
|
||||
return PIndex;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method swaps two elements of an array
|
||||
*
|
||||
* @param array The array to be sorted
|
||||
* @param initial The first element
|
||||
* @param fin The second element
|
||||
* Swaps initial and fin element
|
||||
**/
|
||||
|
||||
public static <T extends Comparable<T>> void swap(T[] array, int initial, int fin) {
|
||||
T temp = array[initial];
|
||||
array[initial] = array[fin];
|
||||
array[fin] = temp;
|
||||
}
|
||||
|
||||
// Driver Program
|
||||
public static void main(String[] args) {
|
||||
|
||||
// For integer input
|
||||
int[] arr = {3,4,1,32,0,2,44,111,5};
|
||||
Integer[] array = new Integer[arr.length];
|
||||
for (int i=0;i<arr.length;i++) {
|
||||
array[i] = arr[i];
|
||||
}
|
||||
|
||||
QS(array, 0, arr.length-1);
|
||||
|
||||
//Output => 0 1 2 3 4 5 32 44 111
|
||||
for (int i=0;i<array.length;i++) {
|
||||
System.out.print(array[i] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
// String Input
|
||||
String[] array1 = {"c", "a", "e", "b","d"};
|
||||
|
||||
QS(array1, 0,array1.length-1);
|
||||
|
||||
//Output => a b c d e
|
||||
for(int i=0; i<array1.length; i++)
|
||||
{
|
||||
System.out.print(array1[i]+"\t");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
73
Sorts/SelectionSort.java
Normal file
73
Sorts/SelectionSort.java
Normal file
@ -0,0 +1,73 @@
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
public class SelectionSort {
|
||||
|
||||
/**
|
||||
* This method implements the Generic Selection Sort
|
||||
*
|
||||
* @param arr The array to be sorted
|
||||
* @param n The count of total number of elements in array
|
||||
* Sorts the array in increasing order
|
||||
**/
|
||||
|
||||
public static <T extends Comparable<T>> void SS(T[] arr, int n) {
|
||||
|
||||
for (int i=0;i<n-1;i++) {
|
||||
|
||||
// Initial index of min
|
||||
int min = i;
|
||||
|
||||
for (int j=i+1;j<n;j++) {
|
||||
if (arr[j].compareTo(arr[min]) < 0) {
|
||||
min = j;
|
||||
}
|
||||
}
|
||||
|
||||
// Swapping if index of min is changed
|
||||
if (min != i) {
|
||||
T temp = arr[i];
|
||||
arr[i] = arr[min];
|
||||
arr[min] = temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Driver Program
|
||||
public static void main(String[] args) {
|
||||
|
||||
// Integer Input
|
||||
int[] arr1 = {4,23,6,78,1,54,231,9,12};
|
||||
int n = arr1.length;
|
||||
|
||||
Integer[] array = new Integer[n];
|
||||
for (int i=0;i<n;i++) {
|
||||
array[i] = arr1[i];
|
||||
}
|
||||
|
||||
SS(array, n);
|
||||
|
||||
// Output => 1 4 6 9 12 23 54 78 231
|
||||
for(int i=0; i<n; i++)
|
||||
{
|
||||
System.out.print(array[i]+"\t");
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
|
||||
// String Input
|
||||
String[] array1 = {"c", "a", "e", "b","d"};
|
||||
n = array1.length;
|
||||
|
||||
SS(array1, n);
|
||||
|
||||
//Output => a b c d e
|
||||
for(int i=0; i<n; i++)
|
||||
{
|
||||
System.out.print(array1[i]+"\t");
|
||||
}
|
||||
}
|
||||
}
|
68
Sorts/ShellSort.java
Normal file
68
Sorts/ShellSort.java
Normal file
@ -0,0 +1,68 @@
|
||||
package Sorts;
|
||||
|
||||
/**
|
||||
* @author dpunosevac
|
||||
*/
|
||||
public class ShellSort {
|
||||
|
||||
/**
|
||||
* This method implements Generic Shell Sort.
|
||||
* @param array The array to be sorted
|
||||
*/
|
||||
public static void shellSort(Comparable[] array) {
|
||||
int N = array.length;
|
||||
int h = 1;
|
||||
|
||||
while (h < N/3) {
|
||||
h = 3 * h + 1;
|
||||
}
|
||||
|
||||
while (h >= 1) {
|
||||
for (int i = h; i < N; i++) {
|
||||
for (int j = i; j >= h && less(array[j], array[j-h]); j -= h) {
|
||||
exch(array, j, j - h);
|
||||
}
|
||||
}
|
||||
|
||||
h /= 3;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method for exchanging places in array
|
||||
* @param array The array which elements we want to swap
|
||||
* @param i index of the first element
|
||||
* @param j index of the second element
|
||||
*/
|
||||
private static void exch(Comparable[] array, int i, int j) {
|
||||
Comparable swap = array[i];
|
||||
array[i] = array[j];
|
||||
array[j] = swap;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method checks if first element is less then the other element
|
||||
* @param v first element
|
||||
* @param w second element
|
||||
* @return true if the first element is less then the second element
|
||||
*/
|
||||
private static boolean less(Comparable v, Comparable w) {
|
||||
return v.compareTo(w) < 0;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Integer Input
|
||||
int[] arr1 = {4,23,6,78,1,54,231,9,12};
|
||||
Integer[] array = new Integer[arr1.length];
|
||||
|
||||
for (int i=0;i<arr1.length;i++) {
|
||||
array[i] = arr1[i];
|
||||
}
|
||||
|
||||
shellSort(array);
|
||||
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
System.out.println(array[i]);
|
||||
}
|
||||
}
|
||||
}
|
67
Sorts/radixSort.java
Normal file
67
Sorts/radixSort.java
Normal file
@ -0,0 +1,67 @@
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
class Radix {
|
||||
|
||||
|
||||
static int getMax(int arr[], int n)
|
||||
{
|
||||
int mx = arr[0];
|
||||
for (int i = 1; i < n; i++)
|
||||
if (arr[i] > mx)
|
||||
mx = arr[i];
|
||||
return mx;
|
||||
}
|
||||
|
||||
static void countSort(int arr[], int n, int exp)
|
||||
{
|
||||
int output[] = new int[n];
|
||||
int i;
|
||||
int count[] = new int[10];
|
||||
Arrays.fill(count,0);
|
||||
|
||||
for (i = 0; i < n; i++)
|
||||
count[ (arr[i]/exp)%10 ]++;
|
||||
|
||||
for (i = 1; i < 10; i++)
|
||||
count[i] += count[i - 1];
|
||||
|
||||
for (i = n - 1; i >= 0; i--)
|
||||
{
|
||||
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
|
||||
count[ (arr[i]/exp)%10 ]--;
|
||||
}
|
||||
|
||||
for (i = 0; i < n; i++)
|
||||
arr[i] = output[i];
|
||||
}
|
||||
|
||||
static void radixsort(int arr[], int n)
|
||||
{
|
||||
|
||||
int m = getMax(arr, n);
|
||||
|
||||
|
||||
for (int exp = 1; m/exp > 0; exp *= 10)
|
||||
countSort(arr, n, exp);
|
||||
}
|
||||
|
||||
|
||||
static void print(int arr[], int n)
|
||||
{
|
||||
for (int i=0; i<n; i++)
|
||||
System.out.print(arr[i]+" ");
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void main (String[] args)
|
||||
{
|
||||
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
|
||||
int n = arr.length;
|
||||
radixsort(arr, n);
|
||||
print(arr, n);
|
||||
}
|
||||
}
|
||||
// Written by James Mc Dermott(theycallmemac)
|
129
data_structures/Graphs/Graphs.java
Normal file
129
data_structures/Graphs/Graphs.java
Normal file
@ -0,0 +1,129 @@
|
||||
import java.util.ArrayList;
|
||||
import java.lang.StringBuilder;
|
||||
|
||||
class AdjacencyListGraph<E extends Comparable<E>> {
|
||||
|
||||
ArrayList<Vertex> verticies;
|
||||
|
||||
public AdjacencyListGraph() {
|
||||
verticies = new ArrayList<>();
|
||||
}
|
||||
|
||||
private class Vertex {
|
||||
E data;
|
||||
ArrayList<Vertex> adjacentVerticies;
|
||||
|
||||
public Vertex(E data) {
|
||||
adjacentVerticies = new ArrayList<>();
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public boolean addAdjacentVertex(Vertex to) {
|
||||
for (Vertex v: adjacentVerticies) {
|
||||
if (v.data.compareTo(to.data) == 0) {
|
||||
return false; // the edge already exists
|
||||
}
|
||||
}
|
||||
return adjacentVerticies.add(to); // this will return true;
|
||||
}
|
||||
|
||||
public boolean removeAdjacentVertex(E to) {
|
||||
// use indexes here so it is possible to
|
||||
// remove easily without implementing
|
||||
// equals method that ArrayList.remove(Object o) uses
|
||||
for (int i = 0; i < adjacentVerticies.size(); i++) {
|
||||
if (adjacentVerticies.get(i).data.compareTo(to) == 0) {
|
||||
adjacentVerticies.remove(i);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* this method removes an edge from the graph between two specified
|
||||
* verticies
|
||||
*
|
||||
* @param from the data of the vertex the edge is from
|
||||
* @param to the data of the vertex the edge is going to
|
||||
* @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
|
||||
*/
|
||||
public boolean removeEdge(E from, E to) {
|
||||
Vertex fromV = null;
|
||||
for (Vertex v: verticies) {
|
||||
if (from.compareTo(v.data) == 0) {
|
||||
fromV = v;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (fromV == null) return false;
|
||||
return fromV.removeAdjacentVertex(to);
|
||||
}
|
||||
/**
|
||||
* this method adds an edge to the graph between two specified
|
||||
* verticies
|
||||
*
|
||||
* @param from the data of the vertex the edge is from
|
||||
* @param to the data of the vertex the edge is going to
|
||||
* @return returns true if the edge did not exist, return false if it already did
|
||||
*/
|
||||
public boolean addEdge(E from, E to) {
|
||||
Vertex fromV = null, toV = null;
|
||||
for (Vertex v: verticies) {
|
||||
if (from.compareTo(v.data) == 0) { // see if from vertex already exists
|
||||
fromV = v;
|
||||
} else if (to.compareTo(v.data) == 0) { // see if to vertex already exists
|
||||
toV = v;
|
||||
}
|
||||
if (fromV != null && toV != null) break; // both nodes exist so stop searching
|
||||
}
|
||||
if (fromV == null) {
|
||||
fromV = new Vertex(from);
|
||||
verticies.add(fromV);
|
||||
}
|
||||
if (toV == null) {
|
||||
toV = new Vertex(to);
|
||||
verticies.add(toV);
|
||||
}
|
||||
return fromV.addAdjacentVertex(toV);
|
||||
}
|
||||
|
||||
/**
|
||||
* this gives a list of verticies in the graph and their adjacencies
|
||||
*
|
||||
* @return returns a string describing this graph
|
||||
*/
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Vertex v: verticies) {
|
||||
sb.append("Vertex: ");
|
||||
sb.append(v.data);
|
||||
sb.append("\n");
|
||||
sb.append("Adjacent verticies: ");
|
||||
for (Vertex v2: v.adjacentVerticies) {
|
||||
sb.append(v2.data);
|
||||
sb.append(" ");
|
||||
}
|
||||
sb.append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public class Graphs {
|
||||
|
||||
public static void main(String args[]) {
|
||||
AdjacencyListGraph<Integer> graph = new AdjacencyListGraph<>();
|
||||
assert graph.addEdge(1, 2);
|
||||
assert graph.addEdge(1, 5);
|
||||
assert graph.addEdge(2, 5);
|
||||
assert !graph.addEdge(1, 2);
|
||||
assert graph.addEdge(2, 3);
|
||||
assert graph.addEdge(3, 4);
|
||||
assert graph.addEdge(4, 1);
|
||||
assert !graph.addEdge(2, 3);
|
||||
System.out.println(graph);
|
||||
}
|
||||
|
||||
}
|
62
data_structures/Graphs/bfs.java
Normal file
62
data_structures/Graphs/bfs.java
Normal file
@ -0,0 +1,62 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Implementation of a Breadth First Search
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
public class bfs{
|
||||
|
||||
/**
|
||||
* The BFS implemented in code to use.
|
||||
*
|
||||
* @param a Structure to perform the search on a graph, adjacency matrix etc.
|
||||
* @param vertices The vertices to use
|
||||
* @param source The Source
|
||||
*/
|
||||
public static void bfsImplement(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
|
||||
byte []b=new byte[vertices]; //flag container containing status of each vertices
|
||||
Arrays.fill(b,(byte)-1); //status initialization
|
||||
/* code status
|
||||
-1 = ready
|
||||
0 = waiting
|
||||
1 = processed */
|
||||
|
||||
Stack st = new Stack(vertices); //operational stack
|
||||
st.push(source); //assigning source
|
||||
while(!st.isEmpty()){
|
||||
b[st.peek()]=(byte)0; //assigning waiting status
|
||||
System.out.println(st.peek());
|
||||
int pop=st.peek();
|
||||
b[pop]=(byte)1; //assigning processed status
|
||||
st.pop(); //removing head of the queue
|
||||
for(int i=0;i<vertices;i++){
|
||||
if(a[pop][i]!=0 && b[i]!=(byte)0 && b[i]!=(byte)1 ){
|
||||
st.push(i);
|
||||
b[i]=(byte)0; //assigning waiting status
|
||||
}}}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]){
|
||||
Scanner in=new Scanner(System.in);
|
||||
int vertices=in.nextInt(),source=in.nextInt();
|
||||
byte [][]a=new byte [vertices][vertices];
|
||||
//initially all elements of a are initialized with value zero
|
||||
|
||||
for(int i=0;i<vertices;i++){
|
||||
int size =in.nextInt();
|
||||
for(int j=0;j<size;j++){
|
||||
a[i][in.nextInt()]=1; //taking adjacency entries by assigning 1
|
||||
}
|
||||
}
|
||||
bfsImplement(a,vertices,source); //function call
|
||||
in.close();
|
||||
}
|
||||
}
|
63
data_structures/Graphs/dfs.java
Normal file
63
data_structures/Graphs/dfs.java
Normal file
@ -0,0 +1,63 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Implementation of a Depth First Search
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
|
||||
public class dfs{
|
||||
|
||||
/**
|
||||
* Implementation in code of a DFS
|
||||
*
|
||||
* @param a structure to be DFS'ed
|
||||
* @param vertices The vertices
|
||||
* @param source The source
|
||||
*/
|
||||
public static void dfsImplement(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
|
||||
byte []b=new byte[vertices]; //flag container containing status of each vertices
|
||||
Arrays.fill(b,(byte)-1); //status initialization
|
||||
/* code status
|
||||
-1 = ready
|
||||
0 = waiting
|
||||
1 = processed */
|
||||
|
||||
|
||||
Stack st=new Stack(vertices); //operational stack
|
||||
st.push(source); //assigning source
|
||||
while(!st.isEmpty()){
|
||||
b[st.peek()]=(byte)0; //assigning waiting status
|
||||
System.out.println(st.peek());
|
||||
int pop=st.pop();
|
||||
b[pop]=(byte)1; //assigning processed status
|
||||
for(int i=0;i<vertices;i++){
|
||||
if(a[pop][i]!=0 && b[i]!=(byte)0 && b[i]!=(byte)1 ){
|
||||
st.push(i);
|
||||
b[i]=(byte)0; //assigning waiting status
|
||||
}}}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]){
|
||||
Scanner in=new Scanner(System.in);
|
||||
int vertices=in.nextInt(),source=in.nextInt();
|
||||
byte [][]a=new byte [vertices][vertices];
|
||||
//initially all elements of a are initialized with value zero
|
||||
|
||||
for(int i=0;i<vertices;i++){
|
||||
int size =in.nextInt();
|
||||
for(int j=0;j<size;j++){
|
||||
a[i][in.nextInt()]=1; //taking adjacency entries by assigning 1
|
||||
}
|
||||
}
|
||||
dfsImplement(a,vertices,source); //function call
|
||||
in.close();
|
||||
}
|
||||
}
|
141
data_structures/HashMap/HashMap.java
Normal file
141
data_structures/HashMap/HashMap.java
Normal file
@ -0,0 +1,141 @@
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class HashMap<K,V> {
|
||||
public class hmnodes{ //HashMap nodes
|
||||
K key;
|
||||
V value;
|
||||
}
|
||||
|
||||
private int size=0; //size of hashmap
|
||||
private LinkedList<hmnodes> buckets[]; //array of addresses of list
|
||||
|
||||
public HashMap(){
|
||||
buckets=new LinkedList[4]; //initially create bucket of any size
|
||||
for(int i=0;i<4;i++)
|
||||
buckets[i]=new LinkedList<>();
|
||||
}
|
||||
|
||||
public void put(K key,V value) throws Exception{
|
||||
int bi=bucketIndex(key); //find the index,the new key will be inserted in linklist at that index
|
||||
int fountAt=find(bi,key); //check if key already exists or not
|
||||
if(fountAt==-1){
|
||||
hmnodes temp=new hmnodes(); //if doesn't exist create new node and insert
|
||||
temp.key=key;
|
||||
temp.value=value;
|
||||
buckets[bi].addLast(temp);
|
||||
this.size++;
|
||||
}else{
|
||||
buckets[bi].get(fountAt).value=value;//if already exist modify the value
|
||||
}
|
||||
|
||||
double lambda = (this.size*1.0)/this.buckets.length;
|
||||
if(lambda>2.0){
|
||||
rehash(); //rehashing function which will increase the size of bucket as soon as lambda exceeds 2.0
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
public V get(K key) throws Exception{
|
||||
int bi=bucketIndex(key);
|
||||
int fountAt=find(bi,key);
|
||||
if(fountAt==-1){
|
||||
return null;
|
||||
}else{
|
||||
return buckets[bi].get(fountAt).value;
|
||||
}
|
||||
}
|
||||
|
||||
public V remove(K key) throws Exception{
|
||||
int bi=bucketIndex(key);
|
||||
int fountAt=find(bi,key);
|
||||
if(fountAt==-1){
|
||||
return null;
|
||||
}else{
|
||||
this.size--;
|
||||
return buckets[bi].remove(fountAt).value;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean containskey(K key) throws Exception{
|
||||
int bi=bucketIndex(key);
|
||||
int fountAt=find(bi,key);
|
||||
if(fountAt==-1){
|
||||
return false;
|
||||
}else{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public int size(){
|
||||
return this.size;
|
||||
}
|
||||
|
||||
|
||||
public boolean isempty(){
|
||||
return this.size==0;
|
||||
}
|
||||
|
||||
public ArrayList<K> keyset() throws Exception{
|
||||
ArrayList<K> arr=new ArrayList<>();
|
||||
for(int i=0;i<buckets.length;i++){
|
||||
for(int j=0;j<buckets[i].size();j++){
|
||||
arr.add(buckets[i].get(j).key);
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public ArrayList<V> valueset() throws Exception{
|
||||
ArrayList<V> arr=new ArrayList<>();
|
||||
for(int i=0;i<buckets.length;i++){
|
||||
for(int j=0;j<buckets[i].size();j++){
|
||||
arr.add(buckets[i].get(j).value);
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public void display() throws Exception{
|
||||
for(int i=0;i<buckets.length;i++){
|
||||
System.out.print("Bucket: "+i+" ");
|
||||
for(int j=0;j<buckets[i].size();j++){
|
||||
hmnodes temp=buckets[i].get(j);
|
||||
System.out.print("["+temp.key+"->"+temp.value+"]");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
|
||||
public int find(int bi,K key) throws Exception{
|
||||
for(int i=0;i<buckets[bi].size();i++){
|
||||
if(key.equals(buckets[bi].get(i).key))
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int bucketIndex(K key) throws Exception{
|
||||
int bi=key.hashCode();
|
||||
return Math.abs(bi%buckets.length);
|
||||
}
|
||||
|
||||
private void rehash() throws Exception{
|
||||
LinkedList<hmnodes> ob[]= buckets;
|
||||
buckets=new LinkedList[ob.length*2];
|
||||
for(int i=0;i<ob.length*2;i++)
|
||||
buckets[i]=new LinkedList<>();
|
||||
|
||||
size = 0;
|
||||
for(int i=0;i<ob.length;i++){
|
||||
for(int j=0;j<ob[i].size();j++){
|
||||
put(ob[i].get(j).key,ob[i].get(j).value);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
42
data_structures/Lists/CircleLinkedList.java
Normal file
42
data_structures/Lists/CircleLinkedList.java
Normal file
@ -0,0 +1,42 @@
|
||||
public class CircleLinkedList<E>{
|
||||
private static class Node<E>{
|
||||
Node<E> next;
|
||||
E value;
|
||||
private Node(E value, Node<E> next){
|
||||
this.value = value;
|
||||
this.next = next;
|
||||
}
|
||||
}
|
||||
private int size; //For better O.O design this should be private allows for better black box design
|
||||
private Node<E> head; //this will point to dummy node;
|
||||
public CircleLinkedList(){ //constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty;
|
||||
head = new Node<E>(null,head); //creation of the dummy node
|
||||
size = 0;
|
||||
}
|
||||
public int getSize(){ return size;} // getter for the size... needed because size is private.
|
||||
public void append(E value){ // for the sake of simplistiy this class will only contain the append function or addLast other add functions can be implemented however this is the basses of them all really.
|
||||
if(value == null){
|
||||
throw new NullPointerException("Cannot add null element to the list"); // we do not want to add null elements to the list.
|
||||
}
|
||||
head.next = new Node<E>(value,head); //head.next points to the last element;
|
||||
size++;}
|
||||
public E remove(int pos){
|
||||
if(pos>size || pos< 0){
|
||||
throw new IndexOutOfBoundsException("position cannot be greater than size or negative"); //catching errors
|
||||
}
|
||||
Node<E> iterator = head.next;
|
||||
Node<E> before = head; //we need to keep track of the element before the element we want to remove we can see why bellow.
|
||||
for(int i = 1; i<=pos; i++){
|
||||
iterator = iterator.next;
|
||||
before = before.next;
|
||||
}
|
||||
E saved = iterator.value;
|
||||
before.next = iterator.next; // assigning the next referance to the the element following the element we want to remove... the last element will be assigned to the head.
|
||||
iterator.next = null; // scrubbing
|
||||
iterator.value = null;
|
||||
return saved;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
214
data_structures/Lists/DoublyLinkedList.java
Normal file
214
data_structures/Lists/DoublyLinkedList.java
Normal file
@ -0,0 +1,214 @@
|
||||
/**
|
||||
* This class implements a DoublyLinkedList. This is done using the classes
|
||||
* LinkedList and Link.
|
||||
*
|
||||
* A linked list is simplar to an array, it holds values. However,
|
||||
* links in a linked list do not have indees. With a linked list
|
||||
* you do not need to predetermine it's size as it grows and shrinks
|
||||
* as it is edited. This is an example of a double ended, doubly
|
||||
* linked list. Each link references the next link and the previous
|
||||
* one.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
|
||||
class DoublyLinkedList{
|
||||
/** Head refers to the front of the list */
|
||||
private Link head;
|
||||
/** Tail refers to the back of the list */
|
||||
private Link tail;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public DoublyLinkedList(){
|
||||
head = null;
|
||||
tail = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert an element at the head
|
||||
*
|
||||
* @param x Element to be inserted
|
||||
*/
|
||||
public void insertHead(int x){
|
||||
Link newLink = new Link(x); //Create a new link with a value attached to it
|
||||
if(isEmpty()) //Set the first element added to be the tail
|
||||
tail = newLink;
|
||||
else
|
||||
head.previous = newLink; // newLink <-- currenthead(head)
|
||||
newLink.next = head; // newLink <--> currenthead(head)
|
||||
head = newLink; // newLink(head) <--> oldhead
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert an element at the tail
|
||||
*
|
||||
* @param x Element to be inserted
|
||||
*/
|
||||
public void insertTail(int x){
|
||||
Link newLink = new Link(x);
|
||||
newLink.next = null; // currentTail(tail) newlink -->
|
||||
tail.next = newLink; // currentTail(tail) --> newLink -->
|
||||
newLink.previous = tail; // currentTail(tail) <--> newLink -->
|
||||
tail = newLink; // oldTail <--> newLink(tail) -->
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the element at the head
|
||||
*
|
||||
* @return The new head
|
||||
*/
|
||||
public Link deleteHead(){
|
||||
Link temp = head;
|
||||
head = head.next; // oldHead <--> 2ndElement(head)
|
||||
head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
|
||||
if(head == null)
|
||||
tail = null;
|
||||
return temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the element at the tail
|
||||
*
|
||||
* @return The new tail
|
||||
*/
|
||||
public Link deleteTail(){
|
||||
Link temp = tail;
|
||||
tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null
|
||||
tail.next = null; // 2ndLast(tail) --> null
|
||||
return temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the element from somewhere in the list
|
||||
*
|
||||
* @param x element to be deleted
|
||||
* @return Link deleted
|
||||
*/
|
||||
public Link delete(int x){
|
||||
Link current = head;
|
||||
|
||||
while(current.value != x) //Find the position to delete
|
||||
current = current.next;
|
||||
|
||||
if(current == head)
|
||||
deleteHead();
|
||||
|
||||
else if(current == tail)
|
||||
deleteTail();
|
||||
|
||||
else{ //Before: 1 <--> 2(current) <--> 3
|
||||
current.previous.next = current.next; // 1 --> 3
|
||||
current.next.previous = current.previous; // 1 <--> 3
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts element and reorders
|
||||
*
|
||||
* @param x Element to be added
|
||||
*/
|
||||
public void insertOrdered(int x){
|
||||
Link newLink = new Link(x);
|
||||
Link current = head;
|
||||
while(current != null && x > current.value) //Find the position to insert
|
||||
current = current.next;
|
||||
|
||||
if(current == head)
|
||||
insertHead(x);
|
||||
|
||||
else if(current == null)
|
||||
insertTail(x);
|
||||
|
||||
else{ //Before: 1 <--> 2(current) <--> 3
|
||||
newLink.previous = current.previous; // 1 <-- newLink
|
||||
current.previous.next = newLink; // 1 <--> newLink
|
||||
newLink.next = current; // 1 <--> newLink --> 2(current) <--> 3
|
||||
current.previous = newLink; // 1 <--> newLink <--> 2(current) <--> 3
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if list is empty
|
||||
*
|
||||
* @return true if list is empty
|
||||
*/
|
||||
public boolean isEmpty(){
|
||||
return(head == null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints contents of the list
|
||||
*/
|
||||
public void display(){ //Prints contents of the list
|
||||
Link current = head;
|
||||
while(current!=null){
|
||||
current.displayLink();
|
||||
current = current.next;
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This class is used to implement the nodes of the
|
||||
* linked list.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Link{
|
||||
/** Value of node */
|
||||
public int value;
|
||||
/** This points to the link in front of the new link */
|
||||
public Link next;
|
||||
/** This points to the link behind the new link */
|
||||
public Link previous;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param value Value of node
|
||||
*/
|
||||
public Link(int value){
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the node
|
||||
*/
|
||||
public void displayLink(){
|
||||
System.out.print(value+" ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Main Method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]){
|
||||
DoublyLinkedList myList = new DoublyLinkedList();
|
||||
|
||||
myList.insertHead(13);
|
||||
myList.insertHead(7);
|
||||
myList.insertHead(10);
|
||||
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
|
||||
|
||||
myList.insertTail(11);
|
||||
myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) -->
|
||||
|
||||
myList.deleteTail();
|
||||
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
|
||||
|
||||
myList.delete(7);
|
||||
myList.display(); // <-- 10(head) <--> 13(tail) -->
|
||||
|
||||
myList.insertOrdered(23);
|
||||
myList.insertOrdered(67);
|
||||
myList.insertOrdered(3);
|
||||
myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
|
||||
}
|
||||
}
|
151
data_structures/Lists/SinglyLinkedList.java
Normal file
151
data_structures/Lists/SinglyLinkedList.java
Normal file
@ -0,0 +1,151 @@
|
||||
/**
|
||||
* This class implements a SinglyLinked List. This is done
|
||||
* using SinglyLinkedList class and a LinkForLinkedList Class.
|
||||
*
|
||||
* A linked list is implar to an array, it hold values.
|
||||
* However, links in a linked list do not have indexes. With
|
||||
* a linked list you do not need to predetermine it's size as
|
||||
* it gorws and shrinks as it is edited. This is an example of
|
||||
* a singly linked list. Elements can only be added/removed
|
||||
* at the head/front of the list.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class SinglyLinkedList{
|
||||
/**Head refered to the front of the list */
|
||||
private Node head;
|
||||
|
||||
/**
|
||||
* Constructor of SinglyLinkedList
|
||||
*/
|
||||
public SinglyLinkedList(){
|
||||
head = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method inserts an element at the head
|
||||
*
|
||||
* @param x Element to be added
|
||||
*/
|
||||
public void insertHead(int x){
|
||||
Node newNode = new Node(x); //Create a new link with a value attached to it
|
||||
newNode.next = head; //Set the new link to point to the current head
|
||||
head = newNode; //Now set the new link to be the head
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Inserts a new node at a specified position
|
||||
* @param head head node of the linked list
|
||||
* @param data data to be stored in a new node
|
||||
* @param position position at which a new node is to be inserted
|
||||
* @return reference of the head of the linked list
|
||||
*/
|
||||
|
||||
Node InsertNth(Node head, int data, int position) {
|
||||
|
||||
Node newNode = new Node();
|
||||
newNode.data = data;
|
||||
|
||||
if (position == 0) {
|
||||
newNode.next = head;
|
||||
return newNode;
|
||||
}
|
||||
|
||||
Node current = head;
|
||||
|
||||
while (--position > 0) {
|
||||
current = current.next;
|
||||
}
|
||||
|
||||
newNode.next = current.next;
|
||||
current.next = newNode;
|
||||
return head;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method deletes an element at the head
|
||||
*
|
||||
* @return The element deleted
|
||||
*/
|
||||
public Node deleteHead(){
|
||||
Node temp = head;
|
||||
head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head
|
||||
return temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the list is empty
|
||||
*
|
||||
* @return true is list is empty
|
||||
*/
|
||||
public boolean isEmpty(){
|
||||
return(head == null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints contents of the list
|
||||
*/
|
||||
public void display(){
|
||||
Node current = head;
|
||||
while(current!=null){
|
||||
System.out.print(current.getValue()+" ");
|
||||
current = current.next;
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]){
|
||||
SinglyLinkedList myList = new SinglyLinkedList();
|
||||
|
||||
System.out.println(myList.isEmpty()); //Will print true
|
||||
|
||||
myList.insertHead(5);
|
||||
myList.insertHead(7);
|
||||
myList.insertHead(10);
|
||||
|
||||
myList.display(); // 10(head) --> 7 --> 5
|
||||
|
||||
myList.deleteHead();
|
||||
|
||||
myList.display(); // 7(head) --> 5
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This class is the nodes of the SinglyLinked List.
|
||||
* They consist of a vlue and a pointer to the node
|
||||
* after them.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Node{
|
||||
/** The value of the node */
|
||||
public int value;
|
||||
/** Point to the next node */
|
||||
public Node next; //This is what the link will point to
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param valuein Value to be put in the node
|
||||
*/
|
||||
public Node(int valuein){
|
||||
value = valuein;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns value of the node
|
||||
*/
|
||||
public int getValue(){
|
||||
return value;
|
||||
}
|
||||
|
||||
}
|
197
data_structures/Matrix/Matrix.java
Normal file
197
data_structures/Matrix/Matrix.java
Normal file
@ -0,0 +1,197 @@
|
||||
/**
|
||||
* Matrix data-type.
|
||||
*
|
||||
* @author Kyler Smith, 2017
|
||||
*/
|
||||
|
||||
|
||||
public class Matrix {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
int[][] data1 = new int[0][0];
|
||||
int[][] data2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
|
||||
int[][] data3 = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};
|
||||
|
||||
Matrix m1 = new Matrix(data1);
|
||||
Matrix m2 = new Matrix(data2);
|
||||
Matrix m3 = new Matrix(data3);
|
||||
|
||||
System.out.println("m1 --> Rows: " + m1.getRows() + " Columns: " + m1.getColumns());
|
||||
System.out.println("m2 --> Rows: " + m2.getRows() + " Columns: " + m2.getColumns());
|
||||
System.out.println("m3 --> Rows: " + m3.getRows() + " Columns: " + m3.getColumns());
|
||||
|
||||
//check for reference issues
|
||||
System.out.println("m2 -->\n" + m2);
|
||||
data2[1][1] = 101;
|
||||
System.out.println("m2 -->\n" + m2);
|
||||
|
||||
//test equals
|
||||
System.out.println("m2==null: " + m2.equals(null)); //false
|
||||
System.out.println("m3==\"MATRIX\": " + m2.equals("MATRIX")); //false
|
||||
System.out.println("m2==m1: " + m2.equals(m1)); //false
|
||||
System.out.println("m2==m2: " + m2.equals(m2)); //true
|
||||
System.out.println("m2==m3: " + m2.equals(m3)); //false
|
||||
|
||||
//test operations (valid)
|
||||
System.out.println("2 * m2:\n" + m2.scale(2));
|
||||
System.out.println("m2 + m3:\n" + m2.plus(m3));
|
||||
System.out.println("m2 - m3:\n" + m2.minus(m3));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Data needs to be a deep copy as not to change the original state.
|
||||
*/
|
||||
private int[][] data;
|
||||
|
||||
/**
|
||||
* Constructor for the matrix takes in a 2D array
|
||||
*
|
||||
* @param pData
|
||||
*/
|
||||
public Matrix(int[][] pData) {
|
||||
|
||||
/** Make a deep copy of the data */
|
||||
if(pData.length != 0) {
|
||||
int[][] newData = new int[pData.length][pData[0].length];
|
||||
|
||||
for(int i = 0; i < pData.length; i++)
|
||||
for(int j = 0; j < pData[0].length; j++)
|
||||
newData[i][j] = pData[i][j];
|
||||
|
||||
this.data = newData;
|
||||
} else {
|
||||
this.data = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the element specified by the given location
|
||||
*
|
||||
* @param x : x cooridinate
|
||||
* @param y : y cooridinate
|
||||
* @return int : value at location
|
||||
*/
|
||||
public int getElement(int x, int y) {
|
||||
return data[x][y];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of rows in the Matrix
|
||||
*
|
||||
* @return rows
|
||||
*/
|
||||
public int getRows() {
|
||||
if(this.data == null)
|
||||
return 0;
|
||||
|
||||
return data.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of rows in the Matrix
|
||||
*
|
||||
* @return columns
|
||||
*/
|
||||
public int getColumns() {
|
||||
if(this.data == null)
|
||||
return 0;
|
||||
return data[0].length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns this matrix scaled by a factor. That is, computes sA where s is a
|
||||
* constant and A is a matrix (this object).
|
||||
*
|
||||
* @param scalar : value to scale by
|
||||
* @return A new matrix scaled by the scalar value
|
||||
*/
|
||||
public Matrix scale(int scalar) {
|
||||
|
||||
int[][] newData = new int[this.data.length][this.data[0].length];
|
||||
|
||||
for (int i = 0; i < this.getRows(); ++i)
|
||||
for(int j = 0; j < this.getColumns(); ++j)
|
||||
newData[i][j] = this.data[i][j] * scalar;
|
||||
|
||||
return new Matrix(newData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds this matrix to another matrix.
|
||||
*
|
||||
* @param other : Matrix to be added
|
||||
* @return addend
|
||||
*/
|
||||
public Matrix plus(Matrix other) throws RuntimeException {
|
||||
|
||||
int[][] newData = new int[this.data.length][this.data[0].length];
|
||||
|
||||
if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
|
||||
throw new RuntimeException("Not the same size matrix.");
|
||||
|
||||
for (int i = 0; i < this.getRows(); ++i)
|
||||
for(int j = 0; j < this.getColumns(); ++j)
|
||||
newData[i][j] = this.data[i][j] + other.getElement(i, j);
|
||||
|
||||
return new Matrix(newData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtracts this matrix from another matrix.
|
||||
*
|
||||
* @param other : Matrix to be subtracted
|
||||
* @return difference
|
||||
*/
|
||||
public Matrix minus(Matrix other) throws RuntimeException {
|
||||
|
||||
int[][] newData = new int[this.data.length][this.data[0].length];
|
||||
|
||||
if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
|
||||
throw new RuntimeException("Not the same size matrix.");
|
||||
|
||||
for (int i = 0; i < this.getRows(); ++i)
|
||||
for(int j = 0; j < this.getColumns(); ++j)
|
||||
newData[i][j] = this.data[i][j] - other.getElement(i, j);
|
||||
|
||||
return new Matrix(newData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the matrix passed is equal to this matrix
|
||||
*
|
||||
* @param other : the other matrix
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean equals(Matrix other) {
|
||||
return this == other;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Matrix as a String in the following format
|
||||
*
|
||||
* [ a b c ] ...
|
||||
* [ x y z ] ...
|
||||
* [ i j k ] ...
|
||||
* ...
|
||||
*
|
||||
* @return Matrix as String
|
||||
* TODO: Work formatting for different digit sizes
|
||||
*/
|
||||
public String toString() {
|
||||
String str = "";
|
||||
|
||||
for(int i = 0; i < this.data.length; i++) {
|
||||
str += "[ ";
|
||||
for(int j = 0; j < this.data[0].length; j++) {
|
||||
str += data[i][j];
|
||||
str += " ";
|
||||
}
|
||||
str += "]";
|
||||
str += "\n";
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
}
|
123
data_structures/Queues/PriorityQueues.java
Normal file
123
data_structures/Queues/PriorityQueues.java
Normal file
@ -0,0 +1,123 @@
|
||||
/**
|
||||
* This class implements a PriorityQueue.
|
||||
*
|
||||
* A priority queue adds elements into positions based on their priority.
|
||||
* So the most important elements are placed at the front/on the top.
|
||||
* In this example I give numbers that are bigger, a higher priority.
|
||||
* Queues in theory have no fixed size but when using an array
|
||||
* implementation it does.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class PriorityQueue{
|
||||
/** The max size of the queue */
|
||||
private int maxSize;
|
||||
/** The array for the queue */
|
||||
private int[] queueArray;
|
||||
/** How many items are in the queue */
|
||||
private int nItems;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param size Size of the queue
|
||||
*/
|
||||
public PriorityQueue(int size){
|
||||
maxSize = size;
|
||||
queueArray = new int[size];
|
||||
nItems = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts an element in it's appropriate place
|
||||
*
|
||||
* @param value Value to be inserted
|
||||
*/
|
||||
public void insert(int value){
|
||||
if(nItems == 0){
|
||||
queueArray[0] = value;
|
||||
}
|
||||
else{
|
||||
int j = nItems;
|
||||
while(j > 0 && queueArray[j-1] > value){
|
||||
queueArray[j] = queueArray[j-1]; //Shifts every element up to make room for insertion
|
||||
j--;
|
||||
}
|
||||
queueArray[j] = value; //Once the correct position is found the value is inserted
|
||||
}
|
||||
nItems++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the element from the front of the queue
|
||||
*
|
||||
* @return The element removed
|
||||
*/
|
||||
public int remove(){
|
||||
return queueArray[--nItems];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks what's at the front of the queue
|
||||
*
|
||||
* @return element at the front of the queue
|
||||
*/
|
||||
public int peek(){
|
||||
return queueArray[nItems-1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the queue is empty
|
||||
*
|
||||
* @return true if the queue is empty
|
||||
*/
|
||||
public boolean isEmpty(){
|
||||
return(nItems == 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the queue is full
|
||||
*
|
||||
* @return true if the queue is full
|
||||
*/
|
||||
public boolean isFull(){
|
||||
return(nItems == maxSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of elements in the queue
|
||||
*
|
||||
* @return number of elements in the queue
|
||||
*/
|
||||
public int getSize(){
|
||||
return nItems;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This class implements the PriorityQueue class above.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
public class PriorityQueues{
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command Line Arguments
|
||||
*/
|
||||
public static void main(String args[]){
|
||||
PriorityQueue myQueue = new PriorityQueue(4);
|
||||
myQueue.insert(10);
|
||||
myQueue.insert(2);
|
||||
myQueue.insert(5);
|
||||
myQueue.insert(3);
|
||||
//[2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top
|
||||
|
||||
for(int i = 3; i>=0; i--)
|
||||
System.out.print(myQueue.remove() + " "); //will print the queue in reverse order [10, 5, 3, 2]
|
||||
|
||||
//As you can see, a Priority Queue can be used as a sorting algotithm
|
||||
}
|
||||
}
|
148
data_structures/Queues/Queues.java
Normal file
148
data_structures/Queues/Queues.java
Normal file
@ -0,0 +1,148 @@
|
||||
/**
|
||||
* This implements Queues by using the class Queue.
|
||||
*
|
||||
* A queue data structure functions the same as a real world queue.
|
||||
* The elements that are added first are the first to be removed.
|
||||
* New elements are added to the back/rear of the queue.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Queue{
|
||||
/** Max size of the queue */
|
||||
private int maxSize;
|
||||
/** The array representing the queue */
|
||||
private int[] queueArray;
|
||||
/** Front of the queue */
|
||||
private int front;
|
||||
/** Rear of the queue */
|
||||
private int rear;
|
||||
/** How many items are in the queue */
|
||||
private int nItems;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param size Size of the new queue
|
||||
*/
|
||||
public Queue(int size){
|
||||
maxSize = size;
|
||||
queueArray = new int[size];
|
||||
front = 0;
|
||||
rear = -1;
|
||||
nItems = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts an element at the rear of the queue
|
||||
*
|
||||
* @param x element to be added
|
||||
* @return True if the element was added successfully
|
||||
*/
|
||||
public boolean insert(int x){
|
||||
if(isFull())
|
||||
return false;
|
||||
if(rear == maxSize-1) //If the back of the queue is the end of the array wrap around to the front
|
||||
rear = -1;
|
||||
rear++;
|
||||
queueArray[rear] = x;
|
||||
nItems++;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an element from the front of the queue
|
||||
*
|
||||
* @return the new front of the queue
|
||||
*/
|
||||
public int remove(){ //Remove an element from the front of the queue
|
||||
if(isEmpty()){
|
||||
System.out.println("Queue is empty");
|
||||
return -1;
|
||||
}
|
||||
int temp = queueArray[front];
|
||||
front++;
|
||||
if(front == maxSize) //Dealing with wrap-around again
|
||||
front = 0;
|
||||
nItems--;
|
||||
return temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks what's at the front of the queue
|
||||
*
|
||||
* @return element at the front of the queue
|
||||
*/
|
||||
public int peekFront(){
|
||||
return queueArray[front];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks what's at the rear of the queue
|
||||
*
|
||||
* @return element at the rear of the queue
|
||||
*/
|
||||
public int peekRear(){
|
||||
return queueArray[rear];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the queue is empty
|
||||
*
|
||||
* @return true if the queue is empty
|
||||
*/
|
||||
public boolean isEmpty(){
|
||||
return(nItems == 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the queue is full
|
||||
*
|
||||
* @return true if the queue is full
|
||||
*/
|
||||
public boolean isFull(){
|
||||
return(nItems == maxSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of elements in the queue
|
||||
*
|
||||
* @return number of elements in the queue
|
||||
*/
|
||||
public int getSize(){
|
||||
return nItems;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This class is the example for the Queue class
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
public class Queues{
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]){
|
||||
Queue myQueue = new Queue(4);
|
||||
myQueue.insert(10);
|
||||
myQueue.insert(2);
|
||||
myQueue.insert(5);
|
||||
myQueue.insert(3);
|
||||
//[10(front), 2, 5, 3(rear)]
|
||||
|
||||
System.out.println(myQueue.isFull()); //Will print true
|
||||
|
||||
myQueue.remove(); //Will make 2 the new front, making 10 no longer part of the queue
|
||||
//[10, 2(front), 5, 3(rear)]
|
||||
|
||||
myQueue.insert(7); //Insert 7 at the rear which will be index 0 because of wrap around
|
||||
// [7(rear), 2(front), 5, 3]
|
||||
|
||||
System.out.println(myQueue.peekFront()); //Will print 2
|
||||
System.out.println(myQueue.peekRear()); //Will print 7
|
||||
}
|
||||
}
|
183
data_structures/Stacks/NodeStack.java
Normal file
183
data_structures/Stacks/NodeStack.java
Normal file
@ -0,0 +1,183 @@
|
||||
/**
|
||||
* Implementation of a stack using nodes.
|
||||
* Unlimited size, no arraylist.
|
||||
*
|
||||
* @author Kyler Smith, 2017
|
||||
*/
|
||||
|
||||
|
||||
public class NodeStack<Item> {
|
||||
|
||||
/**
|
||||
* Entry point for the program.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
NodeStack<Integer> Stack = new NodeStack<Integer>();
|
||||
|
||||
Stack.push(3);
|
||||
Stack.push(4);
|
||||
Stack.push(5);
|
||||
System.out.println("Testing :");
|
||||
Stack.print(); // prints : 5 4 3
|
||||
|
||||
Integer x = Stack.pop(); // x = 5
|
||||
Stack.push(1);
|
||||
Stack.push(8);
|
||||
Integer y = Stack.peek(); // y = 8
|
||||
System.out.println("Testing :");
|
||||
Stack.print(); // prints : 8 1 4 3
|
||||
|
||||
System.out.println("Testing :");
|
||||
System.out.println("x : " + x);
|
||||
System.out.println("y : " + y);
|
||||
}
|
||||
|
||||
/**
|
||||
* Information each node should contain.
|
||||
* @value data : information of the value in the node
|
||||
* @value head : the head of the stack
|
||||
* @value next : the next value from this node
|
||||
* @value previous : the last value from this node
|
||||
* @value size : size of the stack
|
||||
*/
|
||||
private Item data;
|
||||
private static NodeStack<?> head;
|
||||
private NodeStack<?> next;
|
||||
private NodeStack<?> previous;
|
||||
private static int size = 0;
|
||||
|
||||
|
||||
/**
|
||||
* Constructors for the NodeStack.
|
||||
*/
|
||||
public NodeStack() {
|
||||
}
|
||||
|
||||
private NodeStack(Item item) {
|
||||
this.data = item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a value onto the stack.
|
||||
*
|
||||
* @param item : value to be put on the stack.
|
||||
*/
|
||||
public void push(Item item) {
|
||||
|
||||
NodeStack<Item> newNs = new NodeStack<Item>(item);
|
||||
|
||||
if(this.isEmpty()) {
|
||||
NodeStack.setHead(new NodeStack<>(item));
|
||||
newNs.setNext(null);
|
||||
newNs.setPrevious(null);
|
||||
} else {
|
||||
newNs.setPrevious(NodeStack.head);
|
||||
NodeStack.head.setNext(newNs);
|
||||
NodeStack.head = newNs;
|
||||
}
|
||||
|
||||
NodeStack.setSize(NodeStack.getSize() + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Value to be taken off the stack.
|
||||
*
|
||||
* @return item : value that is returned.
|
||||
*/
|
||||
public Item pop() {
|
||||
|
||||
Item item = (Item) NodeStack.head.getData();
|
||||
|
||||
NodeStack.head = NodeStack.head.getPrevious();
|
||||
NodeStack.head.setNext(null);
|
||||
|
||||
NodeStack.setSize(NodeStack.getSize() - 1);
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Value that is next to be taken off the stack.
|
||||
*
|
||||
* @return item : the next value that would be popped off the stack.
|
||||
*/
|
||||
public Item peek() {
|
||||
return (Item) NodeStack.head.getData();
|
||||
}
|
||||
|
||||
/**
|
||||
* If the stack is empty or there is a value in.
|
||||
*
|
||||
* @return boolean : whether or not the stack has anything in it.
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return NodeStack.getSize() == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the size of the stack.
|
||||
*
|
||||
* @return int : number of values in the stack.
|
||||
*/
|
||||
public int size() {
|
||||
return NodeStack.getSize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Print the contents of the stack in the following format.
|
||||
*
|
||||
* x <- head (next out)
|
||||
* y
|
||||
* z <- tail (first in)
|
||||
* .
|
||||
* .
|
||||
* .
|
||||
*
|
||||
*/
|
||||
public void print() {
|
||||
for(NodeStack<?> n = NodeStack.head; n != null; n = n.previous) {
|
||||
System.out.println(n.getData().toString());
|
||||
}
|
||||
}
|
||||
|
||||
/** Getters and setters (private) */
|
||||
private NodeStack<?> getHead() {
|
||||
return NodeStack.head;
|
||||
}
|
||||
|
||||
private static void setHead(NodeStack<?> ns) {
|
||||
NodeStack.head = ns;
|
||||
}
|
||||
|
||||
private NodeStack<?> getNext() {
|
||||
return next;
|
||||
}
|
||||
|
||||
private void setNext(NodeStack<?> next) {
|
||||
this.next = next;
|
||||
}
|
||||
|
||||
private NodeStack<?> getPrevious() {
|
||||
return previous;
|
||||
}
|
||||
|
||||
private void setPrevious(NodeStack<?> previous) {
|
||||
this.previous = previous;
|
||||
}
|
||||
|
||||
private static int getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
private static void setSize(int size) {
|
||||
NodeStack.size = size;
|
||||
}
|
||||
|
||||
private Item getData() {
|
||||
return this.data;
|
||||
}
|
||||
|
||||
private void setData(Item item) {
|
||||
this.data = item;
|
||||
}
|
||||
}
|
221
data_structures/Stacks/Stacks.java
Normal file
221
data_structures/Stacks/Stacks.java
Normal file
@ -0,0 +1,221 @@
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* This class implements a Stack using two different implementations.
|
||||
* Stack is used with a regular array and Stack2 uses an ArrayList.
|
||||
*
|
||||
* A stack is exactly what it sounds like. An element gets added to the top of
|
||||
* the stack and only the element on the top may be removed. This is an example
|
||||
* of an array implementation of a Stack. So an element can only be added/removed
|
||||
* from the end of the array. In theory stack have no fixed size, but with an
|
||||
* array implementation it does.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Stack{
|
||||
/** The max size of the Stack */
|
||||
private int maxSize;
|
||||
/** The array representation of the Stack */
|
||||
private int[] stackArray;
|
||||
/** The top of the stack */
|
||||
private int top;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param size Size of the Stack
|
||||
*/
|
||||
public Stack(int size){
|
||||
maxSize = size;
|
||||
stackArray = new int[maxSize];
|
||||
top = -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an element to the top of the stack
|
||||
*
|
||||
* @param value The element added
|
||||
*/
|
||||
public void push(int value){
|
||||
if(!isFull()){ //Checks for a full stack
|
||||
top++;
|
||||
stackArray[top] = value;
|
||||
}else{
|
||||
System.out.println("The stack is full, can't insert value");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the top element of the stack and returns the value you've removed
|
||||
*
|
||||
* @return value popped off the Stack
|
||||
*/
|
||||
public int pop(){
|
||||
if(!isEmpty()){ //Checks for an empty stack
|
||||
return stackArray[top--];
|
||||
}else{
|
||||
System.out.println("The stack is already empty");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the element at the top of the stack
|
||||
*
|
||||
* @return element at the top of the stack
|
||||
*/
|
||||
public int peek(){
|
||||
if(!isEmpty()){ //Checks for an empty stack
|
||||
return stackArray[top];
|
||||
}else{
|
||||
System.out.println("The stack is empty, cant peek");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the stack is empty
|
||||
*
|
||||
* @return true if the stack is empty
|
||||
*/
|
||||
public boolean isEmpty(){
|
||||
return(top == -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the stack is full
|
||||
*
|
||||
* @return true if the stack is full
|
||||
*/
|
||||
public boolean isFull(){
|
||||
return(top+1 == maxSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes everything in the Stack
|
||||
*
|
||||
* Doesn't delete elements in the array
|
||||
* but if you call push method after calling
|
||||
* makeEmpty it will overwrite previous
|
||||
* values
|
||||
*/
|
||||
public void makeEmpty(){ //Doesn't delete elements in the array but if you call
|
||||
top = -1; //push method after calling makeEmpty it will overwrite previous values
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is an ArrayList Implementation of stack, Where size is not
|
||||
* a problem we can extend the stack as much as we want.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Stack2{
|
||||
/** ArrayList representation of the stack */
|
||||
ArrayList<Integer> stackList;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
Stack2(){
|
||||
stackList=new ArrayList<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds value to the end of list which
|
||||
* is the top for stack
|
||||
*
|
||||
* @param value value to be added
|
||||
*/
|
||||
void push(int value){
|
||||
stackList.add(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pops last element of list which is indeed
|
||||
* the top for Stack
|
||||
*
|
||||
* @return Element popped
|
||||
*/
|
||||
int pop(){
|
||||
|
||||
if(!isEmpty()){ // checks for an empty Stack
|
||||
|
||||
int popValue=stackList.get(stackList.size()-1);
|
||||
stackList.remove(stackList.size()-1); //removes the poped element from the list
|
||||
return popValue;
|
||||
}
|
||||
else{
|
||||
System.out.print("The stack is already empty ");
|
||||
return -1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for empty Stack
|
||||
*
|
||||
* @return true if stack is empty
|
||||
*/
|
||||
boolean isEmpty(){
|
||||
if(stackList.isEmpty())
|
||||
return true;
|
||||
|
||||
else return false;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Top element of stack
|
||||
*
|
||||
* @return top element of stack
|
||||
*/
|
||||
int peek(){
|
||||
return stackList.get(stackList.size()-1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This class implements the Stack and Stack2 created above
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
public class Stacks{
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]){
|
||||
Stack myStack = new Stack(4); //Declare a stack of maximum size 4
|
||||
//Populate the stack
|
||||
myStack.push(5);
|
||||
myStack.push(8);
|
||||
myStack.push(2);
|
||||
myStack.push(9);
|
||||
|
||||
System.out.println("*********************Stack Array Implementation*********************");
|
||||
System.out.println(myStack.isEmpty()); //will print false
|
||||
System.out.println(myStack.isFull()); //will print true
|
||||
System.out.println(myStack.peek()); //will print 9
|
||||
System.out.println(myStack.pop()); //will print 9
|
||||
System.out.println(myStack.peek()); // will print 2
|
||||
|
||||
Stack2 myStack2 = new Stack2(); //Declare a stack of maximum size 4
|
||||
//Populate the stack
|
||||
myStack2.push(5);
|
||||
myStack2.push(8);
|
||||
myStack2.push(2);
|
||||
myStack2.push(9);
|
||||
|
||||
System.out.println("*********************Stack List Implementation*********************");
|
||||
System.out.println(myStack2.isEmpty()); //will print false
|
||||
System.out.println(myStack2.peek()); //will print 9
|
||||
System.out.println(myStack2.pop()); //will print 9
|
||||
System.out.println(myStack2.peek()); // will print 2
|
||||
System.out.println(myStack2.pop()); //will print 2
|
||||
}
|
||||
}
|
212
data_structures/Trees/AVLTree.java
Normal file
212
data_structures/Trees/AVLTree.java
Normal file
@ -0,0 +1,212 @@
|
||||
public class AVLtree {
|
||||
|
||||
private Node root;
|
||||
|
||||
private class Node {
|
||||
private int key;
|
||||
private int balance;
|
||||
private int height;
|
||||
private Node left, right, parent;
|
||||
|
||||
Node(int k, Node p) {
|
||||
key = k;
|
||||
parent = p;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean insert(int key) {
|
||||
if (root == null)
|
||||
root = new Node(key, null);
|
||||
else {
|
||||
Node n = root;
|
||||
Node parent;
|
||||
while (true) {
|
||||
if (n.key == key)
|
||||
return false;
|
||||
|
||||
parent = n;
|
||||
|
||||
boolean goLeft = n.key > key;
|
||||
n = goLeft ? n.left : n.right;
|
||||
|
||||
if (n == null) {
|
||||
if (goLeft) {
|
||||
parent.left = new Node(key, parent);
|
||||
} else {
|
||||
parent.right = new Node(key, parent);
|
||||
}
|
||||
rebalance(parent);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void delete(Node node){
|
||||
if(node.left == null && node.right == null){
|
||||
if(node.parent == null) root = null;
|
||||
else{
|
||||
Node parent = node.parent;
|
||||
if(parent.left == node){
|
||||
parent.left = null;
|
||||
}else parent.right = null;
|
||||
rebalance(parent);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(node.left!=null){
|
||||
Node child = node.left;
|
||||
while (child.right!=null) child = child.right;
|
||||
node.key = child.key;
|
||||
delete(child);
|
||||
}else{
|
||||
Node child = node.right;
|
||||
while (child.left!=null) child = child.left;
|
||||
node.key = child.key;
|
||||
delete(child);
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(int delKey) {
|
||||
if (root == null)
|
||||
return;
|
||||
Node node = root;
|
||||
Node child = root;
|
||||
|
||||
while (child != null) {
|
||||
node = child;
|
||||
child = delKey >= node.key ? node.right : node.left;
|
||||
if (delKey == node.key) {
|
||||
delete(node);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void rebalance(Node n) {
|
||||
setBalance(n);
|
||||
|
||||
if (n.balance == -2) {
|
||||
if (height(n.left.left) >= height(n.left.right))
|
||||
n = rotateRight(n);
|
||||
else
|
||||
n = rotateLeftThenRight(n);
|
||||
|
||||
} else if (n.balance == 2) {
|
||||
if (height(n.right.right) >= height(n.right.left))
|
||||
n = rotateLeft(n);
|
||||
else
|
||||
n = rotateRightThenLeft(n);
|
||||
}
|
||||
|
||||
if (n.parent != null) {
|
||||
rebalance(n.parent);
|
||||
} else {
|
||||
root = n;
|
||||
}
|
||||
}
|
||||
|
||||
private Node rotateLeft(Node a) {
|
||||
|
||||
Node b = a.right;
|
||||
b.parent = a.parent;
|
||||
|
||||
a.right = b.left;
|
||||
|
||||
if (a.right != null)
|
||||
a.right.parent = a;
|
||||
|
||||
b.left = a;
|
||||
a.parent = b;
|
||||
|
||||
if (b.parent != null) {
|
||||
if (b.parent.right == a) {
|
||||
b.parent.right = b;
|
||||
} else {
|
||||
b.parent.left = b;
|
||||
}
|
||||
}
|
||||
|
||||
setBalance(a, b);
|
||||
|
||||
return b;
|
||||
}
|
||||
|
||||
private Node rotateRight(Node a) {
|
||||
|
||||
Node b = a.left;
|
||||
b.parent = a.parent;
|
||||
|
||||
a.left = b.right;
|
||||
|
||||
if (a.left != null)
|
||||
a.left.parent = a;
|
||||
|
||||
b.right = a;
|
||||
a.parent = b;
|
||||
|
||||
if (b.parent != null) {
|
||||
if (b.parent.right == a) {
|
||||
b.parent.right = b;
|
||||
} else {
|
||||
b.parent.left = b;
|
||||
}
|
||||
}
|
||||
|
||||
setBalance(a, b);
|
||||
|
||||
return b;
|
||||
}
|
||||
|
||||
private Node rotateLeftThenRight(Node n) {
|
||||
n.left = rotateLeft(n.left);
|
||||
return rotateRight(n);
|
||||
}
|
||||
|
||||
private Node rotateRightThenLeft(Node n) {
|
||||
n.right = rotateRight(n.right);
|
||||
return rotateLeft(n);
|
||||
}
|
||||
|
||||
private int height(Node n) {
|
||||
if (n == null)
|
||||
return -1;
|
||||
return n.height;
|
||||
}
|
||||
|
||||
private void setBalance(Node... nodes) {
|
||||
for (Node n : nodes)
|
||||
reheight(n);
|
||||
n.balance = height(n.right) - height(n.left);
|
||||
}
|
||||
|
||||
public void printBalance() {
|
||||
printBalance(root);
|
||||
}
|
||||
|
||||
private void printBalance(Node n) {
|
||||
if (n != null) {
|
||||
printBalance(n.left);
|
||||
System.out.printf("%s ", n.balance);
|
||||
printBalance(n.right);
|
||||
}
|
||||
}
|
||||
|
||||
private void reheight(Node node){
|
||||
if(node!=null){
|
||||
node.height=1 + Math.max(height(node.left), height(node.right));
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
AVLtree tree = new AVLtree();
|
||||
|
||||
System.out.println("Inserting values 1 to 10");
|
||||
for (int i = 1; i < 10; i++)
|
||||
tree.insert(i);
|
||||
|
||||
System.out.print("Printing balance: ");
|
||||
tree.printBalance();
|
||||
}
|
||||
}
|
270
data_structures/Trees/BinaryTree.java
Normal file
270
data_structures/Trees/BinaryTree.java
Normal file
@ -0,0 +1,270 @@
|
||||
/**
|
||||
* This entire class is used to build a Binary Tree data structure.
|
||||
* There is the Node Class and the Tree Class, both explained below.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* This class implements the nodes that will go on the Binary Tree.
|
||||
* They consist of the data in them, the node to the left, the node
|
||||
* to the right, and the parent from which they came from.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Node{
|
||||
/** Data for the node */
|
||||
public int data;
|
||||
/** The Node to the left of this one */
|
||||
public Node left;
|
||||
/** The Node to the right of this one */
|
||||
public Node right;
|
||||
/** The parent of this node */
|
||||
public Node parent;
|
||||
|
||||
/**
|
||||
* Constructor of Node
|
||||
*
|
||||
* @param value Value to put in the node
|
||||
*/
|
||||
public Node(int value){
|
||||
data = value;
|
||||
left = null;
|
||||
right = null;
|
||||
parent = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* A binary tree is a data structure in which an element
|
||||
* has two successors(children). The left child is usually
|
||||
* smaller than the parent, and the right child is usually
|
||||
* bigger.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Tree{
|
||||
/** The root of the Binary Tree */
|
||||
private Node root;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public Tree(){
|
||||
root = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method to find a Node with a certain value
|
||||
*
|
||||
* @param key Value being looked for
|
||||
* @return The node if it finds it, otherwise returns the parent
|
||||
*/
|
||||
public Node find(int key){
|
||||
Node current = root;
|
||||
Node last = root;
|
||||
while(current != null){
|
||||
last = current;
|
||||
if(key < current.data)
|
||||
current = current.left;
|
||||
else if(key > current.data)
|
||||
current = current.right;
|
||||
//If you find the value return it
|
||||
else
|
||||
return current;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts certain value into the Binary Tree
|
||||
*
|
||||
* @param value Value to be inserted
|
||||
*/
|
||||
public void put(int value){
|
||||
Node newNode = new Node(value);
|
||||
if(root == null)
|
||||
root = newNode;
|
||||
else{
|
||||
//This will return the soon to be parent of the value you're inserting
|
||||
Node parent = find(value);
|
||||
|
||||
//This if/else assigns the new node to be either the left or right child of the parent
|
||||
if(value < parent.data){
|
||||
parent.left = newNode;
|
||||
parent.left.parent = parent;
|
||||
return;
|
||||
}
|
||||
else{
|
||||
parent.right = newNode;
|
||||
parent.right.parent = parent;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a given value from the Binary Tree
|
||||
*
|
||||
* @param value Value to be deleted
|
||||
* @return If the value was deleted
|
||||
*/
|
||||
public boolean remove(int value){
|
||||
//temp is the node to be deleted
|
||||
Node temp = find(value);
|
||||
|
||||
//If the value doesn't exist
|
||||
if(temp.data != value)
|
||||
return false;
|
||||
|
||||
//No children
|
||||
if(temp.right == null && temp.left == null){
|
||||
if(temp == root)
|
||||
root = null;
|
||||
|
||||
//This if/else assigns the new node to be either the left or right child of the parent
|
||||
else if(temp.parent.data < temp.data)
|
||||
temp.parent.right = null;
|
||||
else
|
||||
temp.parent.left = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
//Two children
|
||||
else if(temp.left != null && temp.right != null){
|
||||
Node successor = findSuccessor(temp);
|
||||
|
||||
//The left tree of temp is made the left tree of the successor
|
||||
successor.left = temp.left;
|
||||
successor.left.parent = successor;
|
||||
|
||||
//If the successor has a right child, the child's grandparent is it's new parent
|
||||
if(successor.right != null && successor.parent != temp){
|
||||
successor.right.parent = successor.parent;
|
||||
successor.parent.left = successor.right;
|
||||
successor.right = temp.right;
|
||||
successor.right.parent = successor;
|
||||
}
|
||||
if(temp == root){
|
||||
successor.parent = null;
|
||||
root = successor;
|
||||
return true;
|
||||
}
|
||||
|
||||
//If you're not deleting the root
|
||||
else{
|
||||
successor.parent = temp.parent;
|
||||
|
||||
//This if/else assigns the new node to be either the left or right child of the parent
|
||||
if(temp.parent.data < temp.data)
|
||||
temp.parent.right = successor;
|
||||
else
|
||||
temp.parent.left = successor;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
//One child
|
||||
else{
|
||||
//If it has a right child
|
||||
if(temp.right != null){
|
||||
if(temp == root){
|
||||
root = temp.right; return true;}
|
||||
|
||||
temp.right.parent = temp.parent;
|
||||
|
||||
//Assigns temp to left or right child
|
||||
if(temp.data < temp.parent.data)
|
||||
temp.parent.left = temp.right;
|
||||
else
|
||||
temp.parent.right = temp.right;
|
||||
return true;
|
||||
}
|
||||
//If it has a left child
|
||||
else{
|
||||
if(temp == root){
|
||||
root = temp.left; return true;}
|
||||
|
||||
temp.left.parent = temp.parent;
|
||||
|
||||
//Assigns temp to left or right side
|
||||
if(temp.data < temp.parent.data)
|
||||
temp.parent.left = temp.left;
|
||||
else
|
||||
temp.parent.right = temp.left;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method finds the Successor to the Node given.
|
||||
* Move right once and go left down the tree as far as you can
|
||||
*
|
||||
* @param n Node that you want to find the Successor of
|
||||
* @return The Successor of the node
|
||||
*/
|
||||
public Node findSuccessor(Node n){
|
||||
if(n.right == null)
|
||||
return n;
|
||||
Node current = n.right;
|
||||
Node parent = n.right;
|
||||
while(current != null){
|
||||
parent = current;
|
||||
current = current.left;
|
||||
}
|
||||
return parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the root of the Binary Tree
|
||||
*
|
||||
* @return the root of the Binary Tree
|
||||
*/
|
||||
public Node getRoot(){
|
||||
return root;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints leftChild - root - rightChild
|
||||
*
|
||||
* @param localRoot The local root of the binary tree
|
||||
*/
|
||||
public void inOrder(Node localRoot){
|
||||
if(localRoot != null){
|
||||
inOrder(localRoot.left);
|
||||
System.out.print(localRoot.data + " ");
|
||||
inOrder(localRoot.right);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints root - leftChild - rightChild
|
||||
*
|
||||
* @param localRoot The local root of the binary tree
|
||||
*/
|
||||
public void preOrder(Node localRoot){
|
||||
if(localRoot != null){
|
||||
System.out.print(localRoot.data + " ");
|
||||
preOrder(localRoot.left);
|
||||
preOrder(localRoot.right);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints rightChild - leftChild - root
|
||||
*
|
||||
* @param localRoot The local root of the binary tree
|
||||
*/
|
||||
public void postOrder(Node localRoot){
|
||||
if(localRoot != null){
|
||||
postOrder(localRoot.left);
|
||||
postOrder(localRoot.right);
|
||||
System.out.print(localRoot.data + " ");
|
||||
}
|
||||
}
|
||||
}
|
226
data_structures/Trees/GenericTree.Java
Normal file
226
data_structures/Trees/GenericTree.Java
Normal file
@ -0,0 +1,226 @@
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class treeclass {
|
||||
private class Node {
|
||||
int data;
|
||||
ArrayList<Node> child = new ArrayList<>();
|
||||
}
|
||||
|
||||
private Node root;
|
||||
private int size;
|
||||
|
||||
/*
|
||||
A generic tree is a tree which can have as many children as it can be
|
||||
It might be possible that every node present is directly connected to
|
||||
root node.
|
||||
|
||||
In this code
|
||||
Every function has two copies: one function is helper function which can be called from
|
||||
main and from that function a private function is called which will do the actual work.
|
||||
I have done this, while calling from main one have to give minimum parameters.
|
||||
|
||||
*/
|
||||
public treeclass() { //Constructor
|
||||
Scanner scn = new Scanner(System.in);
|
||||
root = create_treeG(null, 0, scn);
|
||||
}
|
||||
|
||||
private Node create_treeG(Node node, int childindx, Scanner scn) {
|
||||
// display
|
||||
if (node == null) {
|
||||
System.out.println("Enter root's data");
|
||||
} else {
|
||||
System.out.println("Enter data of parent of index " + node.data + " " + childindx);
|
||||
}
|
||||
// input
|
||||
node = new Node();
|
||||
node.data = scn.nextInt();
|
||||
System.out.println("number of children");
|
||||
int number = scn.nextInt();
|
||||
for (int i = 0; i < number; i++) {
|
||||
Node childd = create_treeG(node, i, scn);
|
||||
size++;
|
||||
node.child.add(childd);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/*
|
||||
Function to display the generic tree
|
||||
*/
|
||||
public void display() { //Helper function
|
||||
display_1(root);
|
||||
return;
|
||||
}
|
||||
|
||||
private void display_1(Node parent) {
|
||||
System.out.print(parent.data + "=>");
|
||||
for (int i = 0; i < parent.child.size(); i++) {
|
||||
System.out.print(parent.child.get(i).data + " ");
|
||||
}
|
||||
System.out.println(".");
|
||||
for (int i = 0; i < parent.child.size(); i++) {
|
||||
display_1(parent.child.get(i));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
One call store the size directly but if you are asked compute size this function to calcuate
|
||||
size goes as follows
|
||||
*/
|
||||
|
||||
public int size2call() {
|
||||
return size2(root);
|
||||
}
|
||||
|
||||
public int size2(Node roott) {
|
||||
int sz = 0;
|
||||
for (int i = 0; i < roott.child.size(); i++) {
|
||||
sz += size2(roott.child.get(i));
|
||||
}
|
||||
return sz + 1;
|
||||
}
|
||||
|
||||
/*
|
||||
Function to compute maximum value in the generic tree
|
||||
*/
|
||||
public int maxcall() {
|
||||
int maxi = root.data;
|
||||
return max(root, maxi);
|
||||
}
|
||||
|
||||
private int max(Node roott, int maxi) {
|
||||
if (maxi < roott.data)
|
||||
maxi = roott.data;
|
||||
for (int i = 0; i < roott.child.size(); i++) {
|
||||
maxi = max(roott.child.get(i), maxi);
|
||||
}
|
||||
|
||||
return maxi;
|
||||
}
|
||||
|
||||
/*
|
||||
Function to compute HEIGHT of the generic tree
|
||||
*/
|
||||
|
||||
public int heightcall() {
|
||||
return height(root) - 1;
|
||||
}
|
||||
|
||||
private int height(Node node) {
|
||||
int h = 0;
|
||||
for (int i = 0; i < node.child.size(); i++) {
|
||||
int k = height(node.child.get(i));
|
||||
if (k > h)
|
||||
h = k;
|
||||
}
|
||||
return h + 1;
|
||||
}
|
||||
|
||||
/*
|
||||
Function to find whether a number is present in the generic tree or not
|
||||
*/
|
||||
|
||||
public boolean findcall(int info) {
|
||||
return find(root, info);
|
||||
}
|
||||
|
||||
private boolean find(Node node, int info) {
|
||||
if (node.data == info)
|
||||
return true;
|
||||
for (int i = 0; i < node.child.size(); i++) {
|
||||
if (find(node.child.get(i), info))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
Function to calculate depth of generic tree
|
||||
*/
|
||||
public void depthcaller(int dep) {
|
||||
depth(root, dep);
|
||||
}
|
||||
|
||||
public void depth(Node node, int dep) {
|
||||
if (dep == 0) {
|
||||
System.out.println(node.data);
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < node.child.size(); i++)
|
||||
depth(node.child.get(i), dep - 1);
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
Function to print generic tree in pre-order
|
||||
*/
|
||||
public void preordercall() {
|
||||
preorder(root);
|
||||
System.out.println(".");
|
||||
}
|
||||
|
||||
private void preorder(Node node) {
|
||||
System.out.print(node.data + " ");
|
||||
for (int i = 0; i < node.child.size(); i++)
|
||||
preorder(node.child.get(i));
|
||||
}
|
||||
|
||||
/*
|
||||
Function to print generic tree in post-order
|
||||
*/
|
||||
public void postordercall() {
|
||||
postorder(root);
|
||||
System.out.println(".");
|
||||
}
|
||||
|
||||
private void postorder(Node node) {
|
||||
for (int i = 0; i < node.child.size(); i++)
|
||||
postorder(node.child.get(i));
|
||||
System.out.print(node.data + " ");
|
||||
}
|
||||
|
||||
/*
|
||||
Function to print generic tree in level-order
|
||||
*/
|
||||
|
||||
public void levelorder() {
|
||||
LinkedList<Node> q = new LinkedList<>();
|
||||
q.addLast(root);
|
||||
while (!q.isEmpty()) {
|
||||
int k = q.getFirst().data;
|
||||
System.out.print(k + " ");
|
||||
|
||||
for (int i = 0; i < q.getFirst().child.size(); i++) {
|
||||
q.addLast(q.getFirst().child.get(i));
|
||||
}
|
||||
q.removeFirst();
|
||||
}
|
||||
System.out.println(".");
|
||||
}
|
||||
|
||||
/*
|
||||
Function to remove all leaves of generic tree
|
||||
*/
|
||||
public void removeleavescall() {
|
||||
removeleaves(root);
|
||||
}
|
||||
|
||||
private void removeleaves(Node node) {
|
||||
ArrayList<Integer> arr = new ArrayList<>();
|
||||
for (int i = 0; i < node.child.size(); i++) {
|
||||
if (node.child.get(i).child.size() == 0) {
|
||||
arr.add(i);
|
||||
// node.child.remove(i);
|
||||
// i--;
|
||||
} else
|
||||
removeleaves(node.child.get(i));
|
||||
}
|
||||
for (int i = arr.size() - 1; i >= 0; i--) {
|
||||
node.child.remove(arr.get(i) + 0);
|
||||
}
|
||||
}
|
||||
|
92
data_structures/Trees/TreeTraversal.java
Normal file
92
data_structures/Trees/TreeTraversal.java
Normal file
@ -0,0 +1,92 @@
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
// Driver Program
|
||||
public class TreeTraversal {
|
||||
public static void main(String[] args) {
|
||||
Node tree = new Node(5);
|
||||
tree.insert(3);
|
||||
tree.insert(7);
|
||||
|
||||
// Prints 3 5 7
|
||||
tree.printInOrder();
|
||||
System.out.println();
|
||||
|
||||
// Prints 5 3 7
|
||||
tree.printPreOrder();
|
||||
System.out.println();
|
||||
|
||||
// Prints 3 7 5
|
||||
tree.printPostOrder();
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The Node class which initializes a Node of a tree
|
||||
* Consists of all 3 traversal methods: printInOrder, printPostOrder & printPreOrder
|
||||
* printInOrder: LEFT -> ROOT -> RIGHT
|
||||
* printPreOrder: ROOT -> LEFT -> RIGHT
|
||||
* printPostOrder: LEFT -> RIGHT -> ROOT
|
||||
*/
|
||||
class Node {
|
||||
Node left, right;
|
||||
int data;
|
||||
|
||||
public Node(int data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public void insert (int value) {
|
||||
if (value < data) {
|
||||
if (left == null) {
|
||||
left = new Node(value);
|
||||
}
|
||||
else {
|
||||
left.insert(value);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (right == null) {
|
||||
right = new Node(value);
|
||||
}
|
||||
else {
|
||||
right.insert(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void printInOrder() {
|
||||
if (left != null) {
|
||||
left.printInOrder();
|
||||
}
|
||||
System.out.print(data + " ");
|
||||
if (right != null) {
|
||||
right.printInOrder();
|
||||
}
|
||||
}
|
||||
|
||||
public void printPreOrder() {
|
||||
System.out.print(data + " ");
|
||||
if (left != null) {
|
||||
left.printPreOrder();
|
||||
}
|
||||
if (right != null) {
|
||||
right.printPreOrder();
|
||||
}
|
||||
}
|
||||
|
||||
public void printPostOrder() {
|
||||
if (left != null) {
|
||||
left.printPostOrder();
|
||||
}
|
||||
if (right != null) {
|
||||
right.printPostOrder();
|
||||
}
|
||||
System.out.print(data + " ");
|
||||
}
|
||||
}
|
||||
|
18
data_structures/heaps/EmptyHeapException.java
Normal file
18
data_structures/heaps/EmptyHeapException.java
Normal file
@ -0,0 +1,18 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package heaps;
|
||||
|
||||
/**
|
||||
* @author Nicolas Renard
|
||||
* Exception to be thrown if the getElement method is used on an empty heap.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class EmptyHeapException extends Exception {
|
||||
|
||||
public EmptyHeapException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
}
|
41
data_structures/heaps/Heap.java
Normal file
41
data_structures/heaps/Heap.java
Normal file
@ -0,0 +1,41 @@
|
||||
package heaps;
|
||||
|
||||
/**
|
||||
* Interface common to heap data structures.<br>
|
||||
* <p>Heaps are tree-like data structures that allow storing elements in a specific
|
||||
* way. Each node corresponds to an element and has one parent node (except for the root) and
|
||||
* at most two children nodes. Every element contains a key, and those keys
|
||||
* indicate how the tree shall be built. For instance, for a min-heap, the key of a node shall
|
||||
* be greater than or equal to its parent's and lower than or equal to its children's (the opposite rule applies to a
|
||||
* max-heap).</p>
|
||||
* <p>All heap-related operations (inserting or deleting an element, extracting the min or max) are performed in
|
||||
* O(log n) time.</p>
|
||||
* @author Nicolas Renard
|
||||
*
|
||||
*
|
||||
*/
|
||||
public interface Heap {
|
||||
|
||||
/**
|
||||
*
|
||||
* @return the top element in the heap, the one with lowest key for min-heap or with
|
||||
* the highest key for max-heap
|
||||
* @throws Exception if heap is empty
|
||||
*/
|
||||
public abstract HeapElement getElement() throws EmptyHeapException;
|
||||
/**
|
||||
* Inserts an element in the heap. Adds it to then end and toggle it until it finds its
|
||||
* right position.
|
||||
*
|
||||
* @param element an instance of the HeapElement class.
|
||||
*/
|
||||
public abstract void insertElement(HeapElement element);
|
||||
|
||||
/**
|
||||
* Delete an element in the heap.
|
||||
*
|
||||
* @param elementIndex int containing the position in the heap of the element to be deleted.
|
||||
*/
|
||||
public abstract void deleteElement(int elementIndex);
|
||||
|
||||
}
|
132
data_structures/heaps/HeapElement.java
Normal file
132
data_structures/heaps/HeapElement.java
Normal file
@ -0,0 +1,132 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package heaps;
|
||||
|
||||
import java.lang.Double;
|
||||
import java.lang.Object;
|
||||
|
||||
/**
|
||||
* Class for heap elements.<br>
|
||||
* <p>A heap element contains two attributes: a key which will be used to build the tree (int
|
||||
* or double, either primitive type or object) and any kind of IMMUTABLE object the user sees fit
|
||||
* to carry any information he/she likes. Be aware that the use of a mutable object might
|
||||
* jeopardize the integrity of this information. </p>
|
||||
* @author Nicolas Renard
|
||||
*
|
||||
*/
|
||||
public class HeapElement {
|
||||
private final double key;
|
||||
private final Object additionalInfo;
|
||||
|
||||
// Constructors
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of primitive type 'double'
|
||||
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
|
||||
* additional information of use for the user
|
||||
*/
|
||||
public HeapElement(double key, Object info) {
|
||||
this.key = key;
|
||||
this.additionalInfo = info;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of primitive type 'int'
|
||||
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
|
||||
* additional information of use for the user
|
||||
*/
|
||||
public HeapElement(int key, Object info) {
|
||||
this.key = key;
|
||||
this.additionalInfo = info;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of object type 'Integer'
|
||||
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
|
||||
* additional information of use for the user
|
||||
*/
|
||||
public HeapElement(Integer key, Object info) {
|
||||
this.key = key;
|
||||
this.additionalInfo = info;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of object type 'Double'
|
||||
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
|
||||
* additional information of use for the user
|
||||
*/
|
||||
public HeapElement(Double key, Object info) {
|
||||
this.key = key;
|
||||
this.additionalInfo = info;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of primitive type 'double'
|
||||
*/
|
||||
public HeapElement(double key) {
|
||||
this.key = key;
|
||||
this.additionalInfo = null;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of primitive type 'int'
|
||||
*/
|
||||
public HeapElement(int key) {
|
||||
this.key = key;
|
||||
this.additionalInfo = null;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of object type 'Integer'
|
||||
*/
|
||||
public HeapElement(Integer key) {
|
||||
this.key = key;
|
||||
this.additionalInfo = null;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of object type 'Double'
|
||||
*/
|
||||
public HeapElement(Double key) {
|
||||
this.key = key;
|
||||
this.additionalInfo = null;
|
||||
}
|
||||
|
||||
// Getters
|
||||
/**
|
||||
* @return the object containing the additional info provided by the user.
|
||||
*/
|
||||
public Object getInfo() {
|
||||
return additionalInfo;
|
||||
}
|
||||
/**
|
||||
* @return the key value of the element
|
||||
*/
|
||||
public double getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
// Overridden object methods
|
||||
|
||||
public String toString() {
|
||||
return "Key: " + key + " - " +additionalInfo.toString();
|
||||
}
|
||||
/**
|
||||
*
|
||||
* @param otherHeapElement
|
||||
* @return true if the keys on both elements are identical and the additional info objects
|
||||
* are identical.
|
||||
*/
|
||||
public boolean equals(HeapElement otherHeapElement) {
|
||||
return (this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo));
|
||||
}
|
||||
}
|
115
data_structures/heaps/MaxHeap.java
Normal file
115
data_structures/heaps/MaxHeap.java
Normal file
@ -0,0 +1,115 @@
|
||||
package heaps;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Heap tree where a node's key is higher than or equal to its parent's and lower than or equal
|
||||
* to its children's.
|
||||
* @author Nicolas Renard
|
||||
*
|
||||
*/
|
||||
public class MaxHeap implements Heap {
|
||||
|
||||
private final List<HeapElement> maxHeap;
|
||||
|
||||
public MaxHeap(List<HeapElement> listElements) throws Exception {
|
||||
maxHeap = new ArrayList<HeapElement>();
|
||||
for (HeapElement heapElement : listElements) {
|
||||
if (heapElement != null) insertElement(heapElement);
|
||||
else System.out.println("Null element. Not added to heap");
|
||||
}
|
||||
if (maxHeap.size() == 0) System.out.println("No element has been added, empty heap.");
|
||||
}
|
||||
|
||||
// Get the element at a given index. The key for the list is equal to index value - 1
|
||||
public HeapElement getElement(int elementIndex) {
|
||||
if ((elementIndex <= 0) && (elementIndex > maxHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range");
|
||||
return maxHeap.get(elementIndex - 1);
|
||||
}
|
||||
|
||||
// Get the key of the element at a given index
|
||||
private double getElementKey(int elementIndex) {
|
||||
return maxHeap.get(elementIndex - 1).getKey();
|
||||
}
|
||||
|
||||
// Swaps two elements in the heap
|
||||
private void swap(int index1, int index2) {
|
||||
HeapElement temporaryElement = maxHeap.get(index1 - 1);
|
||||
maxHeap.set(index1 - 1, maxHeap.get(index2 - 1));
|
||||
maxHeap.set(index2 - 1, temporaryElement);
|
||||
}
|
||||
|
||||
// Toggle an element up to its right place as long as its key is lower than its parent's
|
||||
private void toggleUp(int elementIndex) {
|
||||
double key = maxHeap.get(elementIndex - 1).getKey();
|
||||
while (getElementKey((int) Math.floor(elementIndex/2)) < key) {
|
||||
swap(elementIndex, (int) Math.floor(elementIndex/2));
|
||||
elementIndex = (int) Math.floor(elementIndex/2);
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle an element down to its right place as long as its key is higher
|
||||
// than any of its children's
|
||||
private void toggleDown(int elementIndex) {
|
||||
double key = maxHeap.get(elementIndex - 1).getKey();
|
||||
boolean wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size())));
|
||||
while ((2*elementIndex <= maxHeap.size()) && wrongOrder) {
|
||||
// Check whether it shall swap the element with its left child or its right one if any.
|
||||
if ((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex*2 + 1) > getElementKey(elementIndex*2))) {
|
||||
swap(elementIndex, 2*elementIndex + 1);
|
||||
elementIndex = 2*elementIndex + 1;
|
||||
}
|
||||
else {
|
||||
swap(elementIndex, 2*elementIndex);
|
||||
elementIndex = 2*elementIndex;
|
||||
}
|
||||
wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size())));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private HeapElement extractMax() {
|
||||
HeapElement result = maxHeap.get(0);
|
||||
deleteElement(0);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insertElement(HeapElement element) {
|
||||
maxHeap.add(element);
|
||||
toggleUp(maxHeap.size());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteElement(int elementIndex) {
|
||||
if (maxHeap.isEmpty())
|
||||
try {
|
||||
throw new EmptyHeapException("Attempt to delete an element from an empty heap");
|
||||
} catch (EmptyHeapException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if ((elementIndex > maxHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range");
|
||||
// The last element in heap replaces the one to be deleted
|
||||
maxHeap.set(elementIndex - 1, getElement(maxHeap.size()));
|
||||
maxHeap.remove(maxHeap.size());
|
||||
// Shall the new element be moved up...
|
||||
if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex);
|
||||
// ... or down ?
|
||||
else if (((2*elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2))) ||
|
||||
((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2)))) toggleDown(elementIndex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HeapElement getElement() throws EmptyHeapException {
|
||||
try {
|
||||
return extractMax();
|
||||
} catch (Exception e) {
|
||||
throw new EmptyHeapException("Heap is empty. Error retrieving element");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
115
data_structures/heaps/MinHeap.java
Normal file
115
data_structures/heaps/MinHeap.java
Normal file
@ -0,0 +1,115 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package heaps;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Heap tree where a node's key is higher than or equal to its parent's and lower than or equal
|
||||
* to its children's.
|
||||
* @author Nicolas Renard
|
||||
*
|
||||
*/
|
||||
public class MinHeap implements Heap {
|
||||
|
||||
private final List<HeapElement> minHeap;
|
||||
|
||||
public MinHeap(List<HeapElement> listElements) throws Exception {
|
||||
minHeap = new ArrayList<HeapElement>();
|
||||
for (HeapElement heapElement : listElements) {
|
||||
if (heapElement != null) insertElement(heapElement);
|
||||
else System.out.println("Null element. Not added to heap");
|
||||
}
|
||||
if (minHeap.size() == 0) System.out.println("No element has been added, empty heap.");
|
||||
}
|
||||
|
||||
// Get the element at a given index. The key for the list is equal to index value - 1
|
||||
public HeapElement getElement(int elementIndex) {
|
||||
if ((elementIndex <= 0) && (elementIndex > minHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range");
|
||||
return minHeap.get(elementIndex - 1);
|
||||
}
|
||||
|
||||
// Get the key of the element at a given index
|
||||
private double getElementKey(int elementIndex) {
|
||||
return minHeap.get(elementIndex - 1).getKey();
|
||||
}
|
||||
|
||||
// Swaps two elements in the heap
|
||||
private void swap(int index1, int index2) {
|
||||
HeapElement temporaryElement = minHeap.get(index1 - 1);
|
||||
minHeap.set(index1 - 1, minHeap.get(index2 - 1));
|
||||
minHeap.set(index2 - 1, temporaryElement);
|
||||
}
|
||||
|
||||
// Toggle an element up to its right place as long as its key is lower than its parent's
|
||||
private void toggleUp(int elementIndex) {
|
||||
double key = minHeap.get(elementIndex - 1).getKey();
|
||||
while (getElementKey((int) Math.floor(elementIndex/2)) > key) {
|
||||
swap(elementIndex, (int) Math.floor(elementIndex/2));
|
||||
elementIndex = (int) Math.floor(elementIndex/2);
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle an element down to its right place as long as its key is higher
|
||||
// than any of its children's
|
||||
private void toggleDown(int elementIndex) {
|
||||
double key = minHeap.get(elementIndex - 1).getKey();
|
||||
boolean wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size())));
|
||||
while ((2*elementIndex <= minHeap.size()) && wrongOrder) {
|
||||
// Check whether it shall swap the element with its left child or its right one if any.
|
||||
if ((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex*2 + 1) < getElementKey(elementIndex*2))) {
|
||||
swap(elementIndex, 2*elementIndex + 1);
|
||||
elementIndex = 2*elementIndex + 1;
|
||||
}
|
||||
else {
|
||||
swap(elementIndex, 2*elementIndex);
|
||||
elementIndex = 2*elementIndex;
|
||||
}
|
||||
wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size())));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private HeapElement extractMin() {
|
||||
HeapElement result = minHeap.get(0);
|
||||
deleteElement(0);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insertElement(HeapElement element) {
|
||||
minHeap.add(element);
|
||||
toggleUp(minHeap.size());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteElement(int elementIndex) {
|
||||
if (minHeap.isEmpty())
|
||||
try {
|
||||
throw new EmptyHeapException("Attempt to delete an element from an empty heap");
|
||||
} catch (EmptyHeapException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if ((elementIndex > minHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range");
|
||||
// The last element in heap replaces the one to be deleted
|
||||
minHeap.set(elementIndex - 1, getElement(minHeap.size()));
|
||||
minHeap.remove(minHeap.size());
|
||||
// Shall the new element be moved up...
|
||||
if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex);
|
||||
// ... or down ?
|
||||
else if (((2*elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2))) ||
|
||||
((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2)))) toggleDown(elementIndex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HeapElement getElement() throws EmptyHeapException {
|
||||
try {
|
||||
return extractMin();
|
||||
} catch (Exception e) {
|
||||
throw new EmptyHeapException("Heap is empty. Error retrieving element");
|
||||
}
|
||||
}
|
||||
}
|
46
insert_delete_in_array.java
Normal file
46
insert_delete_in_array.java
Normal file
@ -0,0 +1,46 @@
|
||||
import java.util.*;
|
||||
public class Array {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner s = new Scanner(System.in); // Input statement
|
||||
System.out.println("Enter the size of the array");
|
||||
int size = s.nextInt();
|
||||
int a[] = new int[size];
|
||||
int i;
|
||||
|
||||
// To enter the initial elements
|
||||
for(i=0;i<size;i++){
|
||||
System.out.println("Enter the element");
|
||||
a[i] = s.nextInt();
|
||||
}
|
||||
|
||||
// To insert a new element(we are creating a new array)
|
||||
System.out.println("Enter the index at which the element should be inserted");
|
||||
int insert_pos = s.nextInt();
|
||||
System.out.println("Enter the element to be inserted");
|
||||
int ins = s.nextInt();
|
||||
int size2 = size + 1;
|
||||
int b[] =new int[size2];
|
||||
for(i=0;i<size2;i++){
|
||||
if(i <= insert_pos){
|
||||
b[i] = a[i];
|
||||
}
|
||||
else{
|
||||
b[i] = a[i-1];
|
||||
}
|
||||
}
|
||||
b[insert_pos] = ins;
|
||||
for(i=0;i<size2;i++){
|
||||
System.out.println(b[i]);
|
||||
}
|
||||
|
||||
// To delete an element given the index
|
||||
System.out.println("Enter the index at which element is to be deleted");
|
||||
int del_pos = s.nextInt();
|
||||
for(i=del_pos;i<size2-1;i++){
|
||||
b[i] = b[i+1];
|
||||
}
|
||||
for(i=0;i<size2-1;i++)
|
||||
System.out.println(b[i]);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user