refactor: format code and fix typos

This commit is contained in:
yanglbme 2019-05-10 14:49:24 +08:00
parent 60bb026f8a
commit 8e8e14d1c2
21 changed files with 524 additions and 516 deletions

View File

@ -3,6 +3,7 @@ package src.main.java.com.conversions;
public class AnyBaseToDecimal { public class AnyBaseToDecimal {
/** /**
* This method produces a decimal value of any given input number of any base * This method produces a decimal value of any given input number of any base
*
* @param inpNum String of which we need the decimal value and base in integer format * @param inpNum String of which we need the decimal value and base in integer format
* @return string format of the decimal value * @return string format of the decimal value
*/ */
@ -12,11 +13,11 @@ public class AnyBaseToDecimal {
int num = 0; int num = 0;
int pow = 1; int pow = 1;
for (int i=len-1; i>=0; i--) { for (int i = len - 1; i >= 0; i--) {
if (valOfChar(inpNum.charAt(i)) >= base) { if (valOfChar(inpNum.charAt(i)) >= base) {
return "Invalid Number"; return "Invalid Number";
} }
num += valOfChar(inpNum.charAt(i))*pow; num += valOfChar(inpNum.charAt(i)) * pow;
pow *= base; pow *= base;
} }
return String.valueOf(num); return String.valueOf(num);
@ -24,16 +25,16 @@ public class AnyBaseToDecimal {
/** /**
* This method produces integer value of the input character and returns it * This method produces integer value of the input character and returns it
*
* @param c Char of which we need the integer value of * @param c Char of which we need the integer value of
* @return integer value of input char * @return integer value of input char
*/ */
private static int valOfChar(char c) { private static int valOfChar(char c) {
if (c >= '0' && c <= '9') { if (c >= '0' && c <= '9') {
return (int)c - '0'; return (int) c - '0';
} } else {
else { return (int) c - 'A' + 10;
return (int)c - 'A' + 10;
} }
} }
} }

View File

@ -11,7 +11,7 @@ public class BinaryToHexadecimal {
* hm to store hexadecimal codes for binary numbers * hm to store hexadecimal codes for binary numbers
* within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15 * within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15
*/ */
private static Map<Integer, String> hmHexadecimal = new HashMap<>(16); private static Map<Integer, String> hmHexadecimal = new HashMap<>(16);
static { static {
int i; int i;

View File

@ -3,23 +3,24 @@ package src.main.java.com.conversions;
import java.util.ArrayList; import java.util.ArrayList;
public class DecimalToAnyBase { public class DecimalToAnyBase {
/** /**
* This method produces a String value of any given input decimal in any base * 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 *
* @param inp Decimal of which we need the value in base in String format
* @param base base in which we want the decimal value to be converted into * @param base base in which we want the decimal value to be converted into
* @return string format of the converted value in the given base * @return string format of the converted value in the given base
*/ */
public String convertToAnyBase(int inp, int base) { public String convertToAnyBase(int inp, int base) {
ArrayList<Character> charArr = new ArrayList<>(); ArrayList<Character> charArr = new ArrayList<>();
while (inp > 0) { while (inp > 0) {
charArr.add(reVal(inp%base)); charArr.add(reVal(inp % base));
inp /= base; inp /= base;
} }
StringBuilder str = new StringBuilder(charArr.size()); StringBuilder str = new StringBuilder(charArr.size());
for(Character ch: charArr) { for (Character ch : charArr) {
str.append(ch); str.append(ch);
} }
@ -28,14 +29,15 @@ public class DecimalToAnyBase {
/** /**
* This method produces character value of the input integer and returns it * This method produces character value of the input integer and returns it
*
* @param num integer of which we need the character value of * @param num integer of which we need the character value of
* @return character value of input integer * @return character value of input integer
*/ */
private char reVal(int num) { private char reVal(int num) {
if (num >= 0 && num <= 9) if (num >= 0 && num <= 9)
return (char)(num + '0'); return (char) (num + '0');
else else
return (char)(num - 10 + 'A'); return (char) (num - 10 + 'A');
} }
} }

View File

@ -3,15 +3,16 @@ package src.main.java.com.conversions;
import java.math.BigInteger; import java.math.BigInteger;
public class DecimalToHexadecimal { public class DecimalToHexadecimal {
private static final char hexChars[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; private static final char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
private static final BigInteger valueHex = new BigInteger("16"); private static final BigInteger valueHex = new BigInteger("16");
/** /**
* This method converts and decimal number to a Hexadecimal number * This method converts and decimal number to a Hexadecimal number
*
* @param decimalStr * @param decimalStr
* @return hexadecimal number * @return hexadecimal number
*/ */
public String decimalToHex(String decimalStr){ public String decimalToHex(String decimalStr) {
BigInteger decimal = new BigInteger(decimalStr); BigInteger decimal = new BigInteger(decimalStr);
int rem; int rem;

View File

@ -3,20 +3,21 @@ package src.main.java.com.conversions;
import java.math.BigInteger; import java.math.BigInteger;
public class DecimalToOctal { public class DecimalToOctal {
private static final char octalChars[] = {'0','1','2','3','4','5','6','7'}; private static final char[] octalChars = {'0', '1', '2', '3', '4', '5', '6', '7'};
private static final BigInteger valueOctal = new BigInteger("8"); private static final BigInteger valueOctal = new BigInteger("8");
/** /**
* This method converts and decimal number to a octal number * This method converts and decimal number to a octal number
*
* @param decimalStr * @param decimalStr
* @return octal number * @return octal number
*/ */
public String decimalToOctal(String decimalStr){ public String decimalToOctal(String decimalStr) {
BigInteger decimal = new BigInteger(decimalStr); BigInteger decimal = new BigInteger(decimalStr);
int rem; int rem;
String octal = ""; String octal = "";
while(decimal.compareTo(BigInteger.ZERO) > 0) { while (decimal.compareTo(BigInteger.ZERO) > 0) {
rem = decimal.mod(valueOctal).intValueExact(); rem = decimal.mod(valueOctal).intValueExact();
octal = octalChars[rem] + octal; octal = octalChars[rem] + octal;
decimal = decimal.divide(valueOctal); decimal = decimal.divide(valueOctal);

View File

@ -2,39 +2,42 @@ package src.main.java.com.dataStructures;
/** /**
* Binary tree for general value type, without redundancy * Binary tree for general value type, without redundancy
* @author RICARDO *
* @param <T> root data * @param <T> root data
*/ */
public class BinaryTree<T extends Comparable> { public class BinaryTree<T extends Comparable> {
private final T data; private final T data;
private BinaryTree right, // the upper binary tree private BinaryTree right, // the upper binary tree
left; // the lower binary tree left; // the lower binary tree
public BinaryTree(T data) { public BinaryTree(T data) {
this.data = data; this.data = data;
} }
@Override @Override
public String toString(){ public String toString() {
return this.data.toString(); return this.data.toString();
} }
/** /**
* inserts a new value in it's correspondant place * inserts a new value in it's correspondant place
* @param newDataValue value of the new banary tree to add on this tree *
* @param newDataValue value of the new binary tree to add on this tree
*/ */
public void insert(T newDataValue){ public void insert(T newDataValue) {
this.insert(new BinaryTree(newDataValue)); this.insert(new BinaryTree(newDataValue));
} }
/** /**
* inserts a new binary tree in it's correspondant place * inserts a new binary tree in it's correspondant place
* @param newData new value to add on this tree *
* @param newData new value to add on this tree
*/ */
public void insert(BinaryTree newData){ public void insert(BinaryTree newData) {
int cpr = newData.data.compareTo(this.data); //new value comparission respect to actual value int cpr = newData.data.compareTo(this.data); //new value comparission respect to actual value
if (cpr < 0) if (cpr < 0)
if (this.left == null) if (this.left == null)
this.setLeft(newData); this.setLeft(newData);
@ -51,12 +54,13 @@ public class BinaryTree<T extends Comparable> {
/** /**
* search and specific value on the tree * search and specific value on the tree
* @param data Searched value *
* @return Binary tree wich contains the value, null if it doesn't exist * @param data Searched value
* @return Binary tree which contains the value, null if it doesn't exist
*/ */
public BinaryTree search(T data){ public BinaryTree search(T data) {
int cpr = data.compareTo(this.data); //new value comparission respect to actual value int cpr = data.compareTo(this.data); //new value comparission respect to actual value
if (cpr < 0) { if (cpr < 0) {
if (this.left == null) if (this.left == null)
return null; //the value doesn't exist return null; //the value doesn't exist
@ -65,43 +69,45 @@ public class BinaryTree<T extends Comparable> {
if (cpr > 0) { if (cpr > 0) {
if (this.right == null) if (this.right == null)
return null; //the value doesn't exist return null; //the value doesn't exist
return this.right.search(data); return this.right.search(data);
} }
return this; return this;
} }
/** /**
* Checks if the data value exist in the tree * Checks if the data value exist in the tree
*
* @param data data to be searched * @param data data to be searched
* @return true if this tree contains the data value, false if not. * @return true if this tree contains the data value, false if not.
*/ */
public boolean contains(T data){ public boolean contains(T data) {
return this.search(data) != null; return this.search(data) != null;
} }
/** /**
* uses recursive black magic to print this tree in console * uses recursive black magic to print this tree in console
*
* @param tabCounter prev tabs * @param tabCounter prev tabs
*/ */
private void print(int tabCounter){ private void print(int tabCounter) {
for (int i = 0; i < tabCounter; i++) for (int i = 0; i < tabCounter; i++)
System.out.print("\t"); System.out.print("\t");
System.out.println(this); System.out.println(this);
if (this.left != null) if (this.left != null)
this.left.print(tabCounter + 1); //it can't be ++ , pls don't change it this.left.print(tabCounter + 1); //it can't be ++ , pls don't change it
if (this.right != null) if (this.right != null)
this.right.print(tabCounter + 1); //it can't be ++ , pls don't change it this.right.print(tabCounter + 1); //it can't be ++ , pls don't change it
} }
/** /**
* uses black magic to print this tree in console * uses black magic to print this tree in console
*/ */
public void print(){ public void print() {
this.print(0); this.print(0);
} }
//getters and setters //getters and setters
public T getData() { public T getData() {
return data; return data;

View File

@ -15,7 +15,6 @@ import java.util.*;
* <p> * <p>
* 2. quickly query two elements whether contained in the same set, requiring about O(1) time. * 2. quickly query two elements whether contained in the same set, requiring about O(1) time.
* *
* @author yangxf
*/ */
public class DisjointSet<T> implements Serializable { public class DisjointSet<T> implements Serializable {
private static final long serialVersionUID = 3134700471905625636L; private static final long serialVersionUID = 3134700471905625636L;

View File

@ -7,128 +7,131 @@ import java.util.Random;
*/ */
public class SimplexNoise { public class SimplexNoise {
private SimplexNoiseOctave[] octaves; private SimplexNoiseOctave[] octaves;
private double[] frequencys; private double[] frequencys;
private double[] amplitudes; private double[] amplitudes;
private int largestFeature; private int largestFeature;
private double persistance; private double persistance;
private long seed; private long seed;
/** /**
* @param largestFeature the diameter of the largest possible "cloud". * @param largestFeature the diameter of the largest possible "cloud".
* @param persistence the persistence. a low persistence causes smoother transition between the features while a high one makes the transition hard. (range = {@code 0.0F} - {@code 1.0F}) * @param persistence the persistence. a low persistence causes smoother transition between the features while a high one makes the transition hard. (range = {@code 0.0F} - {@code 1.0F})
* @param seed the seed this algorithm will use to generate pseudo random numbers. The generation will always look the same if the seed and the other parameters have the same value as in a previous generation * @param seed the seed this algorithm will use to generate pseudo random numbers. The generation will always look the same if the seed and the other parameters have the same value as in a previous generation
*/ */
public SimplexNoise(int largestFeature, double persistence, long seed) { public SimplexNoise(int largestFeature, double persistence, long seed) {
this.largestFeature = largestFeature; this.largestFeature = largestFeature;
this.persistance = persistence; this.persistance = persistence;
this.seed = seed; this.seed = seed;
int octaveCount = (int)Math.ceil(Math.log10(largestFeature) / Math.log10(2.0D)); int octaveCount = (int) Math.ceil(Math.log10(largestFeature) / Math.log10(2.0D));
this.octaves = new SimplexNoiseOctave[octaveCount]; this.octaves = new SimplexNoiseOctave[octaveCount];
this.frequencys = new double[octaveCount]; this.frequencys = new double[octaveCount];
this.amplitudes = new double[octaveCount]; this.amplitudes = new double[octaveCount];
Random random = new Random(seed); Random random = new Random(seed);
for(int index = 0; index < octaveCount; index++) { for (int index = 0; index < octaveCount; index++) {
this.octaves[index] = new SimplexNoiseOctave(random.nextInt()); this.octaves[index] = new SimplexNoiseOctave(random.nextInt());
this.frequencys[index] = Math.pow(2, index); this.frequencys[index] = Math.pow(2, index);
this.amplitudes[index] = Math.pow(persistence, octaveCount - index); this.amplitudes[index] = Math.pow(persistence, octaveCount - index);
} }
} }
/** /**
* Generates a height map. * Generates a height map.
* @param x X coordinate *
* @param y Y coordinate * @param x X coordinate
* @param width width * @param y Y coordinate
* @param height height * @param width width
* @return the generated height map * @param height height
*/ * @return the generated height map
public float[][] generateHeightMap(int x, int y, int width, int height) { */
public float[][] generateHeightMap(int x, int y, int width, int height) {
int xEnd = x + width;
int yEnd = y + height; int xEnd = x + width;
int yEnd = y + height;
float[][] result = new float[width][height];
float[][] result = new float[width][height];
for(int i = 0; i < width; i++) {
for (int i = 0; i < width; i++) {
for(int j = 0; j < height; j++) {
for (int j = 0; j < height; j++) {
int posX = x + i * ((xEnd - x) / width);
int posY = y + j * ((yEnd - y) / height); int posX = x + i * ((xEnd - x) / width);
result[i][j] = Math.min(1.0F, Math.max(0.0F, (float)(0.5D * (1 + this.getNoise(posX, posY))))); int posY = y + j * ((yEnd - y) / height);
} result[i][j] = Math.min(1.0F, Math.max(0.0F, (float) (0.5D * (1 + this.getNoise(posX, posY)))));
} }
}
return result;
} return result;
}
/**
* Generates a two dimensional noise. /**
* @param x X coordinate * Generates a two dimensional noise.
* @param y Y coordinate *
* @return the generated noise * @param x X coordinate
*/ * @param y Y coordinate
public double getNoise(int x, int y) { * @return the generated noise
*/
double result = 0; public double getNoise(int x, int y) {
for(int index = 0; index < this.octaves.length; index++) { double result = 0;
result += this.octaves[index].noise(x / this.frequencys[index], y / this.frequencys[index]) * this.amplitudes[index]; for (int index = 0; index < this.octaves.length; index++) {
}
result += this.octaves[index].noise(x / this.frequencys[index], y / this.frequencys[index]) * this.amplitudes[index];
return result; }
}
return result;
/** }
* Generates a three dimensional noise.
* @param x X coordinate /**
* @param y Y coordinate * Generates a three dimensional noise.
* @param z Z coordinate *
* @return the generated noise * @param x X coordinate
*/ * @param y Y coordinate
public double getNoise(int x, int y, int z) { * @param z Z coordinate
* @return the generated noise
double result = 0; */
public double getNoise(int x, int y, int z) {
for(int index = 0; index < this.octaves.length; index++) {
double result = 0;
double frequency = Math.pow(2, index);
double amplitude = Math.pow(this.persistance, this.octaves.length - index); for (int index = 0; index < this.octaves.length; index++) {
result += this.octaves[index].noise(x / frequency, y / frequency, z / frequency) * amplitude; double frequency = Math.pow(2, index);
} double amplitude = Math.pow(this.persistance, this.octaves.length - index);
return result; result += this.octaves[index].noise(x / frequency, y / frequency, z / frequency) * amplitude;
} }
/** return result;
* @return the largest possible feature }
*/
public int getLargestFeature() { /**
* @return the largest possible feature
return this.largestFeature; */
} public int getLargestFeature() {
/** return this.largestFeature;
* @return the persistence }
*/
public double getPersistance() { /**
* @return the persistence
return this.persistance; */
} public double getPersistance() {
/** return this.persistance;
* @return the seed }
*/
public long getSeed() { /**
* @return the seed
return this.seed; */
} public long getSeed() {
return this.seed;
}
} }

View File

@ -14,7 +14,7 @@ public class SimplexNoiseOctave {
new Gradient(1, 0, -1), new Gradient(-1, 0, -1), new Gradient(0, 1, 1), new Gradient(1, 0, -1), new Gradient(-1, 0, -1), new Gradient(0, 1, 1),
new Gradient(0, -1, 1), new Gradient(0, 1, -1), new Gradient(0, -1, -1) new Gradient(0, -1, 1), new Gradient(0, 1, -1), new Gradient(0, -1, -1)
}; };
private static final short P_SUPPLY[] = { private static final short[] P_SUPPLY = {
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,

View File

@ -5,8 +5,8 @@ public class GaleShapley {
/** /**
* Return a stable matching between men and women according to their preferences, * Return a stable matching between men and women according to their preferences,
* following the Gale-Shapley algorithm. * following the Gale-Shapley algorithm.
* *
* @param menPrefs for each man, for each preference rank, the corresponding woman * @param menPrefs for each man, for each preference rank, the corresponding woman
* @param womenPrefs for each woman, for each preference rank, the corresponding man * @param womenPrefs for each woman, for each preference rank, the corresponding man
* @return for each man, the associated woman (1-dimensional array) * @return for each man, the associated woman (1-dimensional array)
*/ */
@ -88,7 +88,7 @@ public class GaleShapley {
/** /**
* Get a currently unengaged man, if there is one * Get a currently unengaged man, if there is one
* *
* @param menMatching the current men matching array (being constructed) * @param menMatching the current men matching array (being constructed)
* @return the first man that is not engaged, or -1 if all men are engaged * @return the first man that is not engaged, or -1 if all men are engaged
*/ */

View File

@ -16,7 +16,6 @@ import java.util.function.Function;
* <p> * <p>
* The accuracy rate depends on capacity and hash functions. * The accuracy rate depends on capacity and hash functions.
* *
* @author yangxf
*/ */
public class BloomFilter implements Serializable { public class BloomFilter implements Serializable {
private static final long serialVersionUID = -4466610350741278658L; private static final long serialVersionUID = -4466610350741278658L;

View File

@ -15,7 +15,7 @@ public final class LinearSearch {
* @param <T> is any comparable type * @param <T> is any comparable type
* @return index of the element * @return index of the element
*/ */
public static <T extends Comparable<T>> int findIndex(T array[], T key) { public static <T extends Comparable<T>> int findIndex(T[] array, T key) {
return search(array, key); return search(array, key);
} }
@ -24,7 +24,7 @@ public final class LinearSearch {
* @param key The element you are looking for * @param key The element you are looking for
* @return the location of the key or -1 if the element is not found * @return the location of the key or -1 if the element is not found
**/ **/
private static <T extends Comparable<T>> int search(T array[], T key){ private static <T extends Comparable<T>> int search(T[] array, T key){
for(int i = 0; i < array.length;i++) { for(int i = 0; i < array.length;i++) {
if (array[i].compareTo(key) == 0){ if (array[i].compareTo(key) == 0){
return i; return i;

View File

@ -9,107 +9,106 @@ import static src.main.java.com.sorts.SortUtils.swap;
public class HeapSort { public class HeapSort {
private static class Heap<T extends Comparable<T>> {
/**
* Array to store heap
*/
private T[] heap;
private static class Heap<T extends Comparable<T>> { /**
/** * Constructor
* Array to store heap *
*/ * @param heap array of unordered integers
private T[] heap; */
Heap(T[] heap) {
/** this.heap = heap;
* Constructor
*
* @param heap array of unordered integers
*/
Heap(T[] heap) {
this.heap = heap;
}
/**
* 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;
T root = heap[rootIndex];
if (rightIndex <= lastChild) {
// if has right and left children
T left = heap[leftIndex];
T right = heap[rightIndex];
if (less(left, right) && less(left, root)) {
swap(heap, leftIndex, rootIndex);
heapSubtree(leftIndex, lastChild);
} else if (less(right, root)) {
swap(heap, rightIndex, rootIndex);
heapSubtree(rightIndex, lastChild);
} }
} else if (leftIndex <= lastChild) {
// if no right child, but has left child /**
T left = heap[leftIndex]; * Heapifies subtree from top as root to last as last child
if (less(left, root)) { *
swap(heap, leftIndex, rootIndex); * @param rootIndex index of root
heapSubtree(leftIndex, lastChild); * @param lastChild index of last child
*/
private void heapSubtree(int rootIndex, int lastChild) {
int leftIndex = rootIndex * 2 + 1;
int rightIndex = rootIndex * 2 + 2;
T root = heap[rootIndex];
if (rightIndex <= lastChild) {
// if has right and left children
T left = heap[leftIndex];
T right = heap[rightIndex];
if (less(left, right) && less(left, root)) {
swap(heap, leftIndex, rootIndex);
heapSubtree(leftIndex, lastChild);
} else if (less(right, root)) {
swap(heap, rightIndex, rootIndex);
heapSubtree(rightIndex, lastChild);
}
} else if (leftIndex <= lastChild) {
// if no right child, but has left child
T left = heap[leftIndex];
if (less(left, root)) {
swap(heap, leftIndex, rootIndex);
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 < heap.length;
boolean hasRightChild = rightIndex < heap.length;
if (hasRightChild) {
//if has left and right
makeMinHeap(leftIndex);
makeMinHeap(rightIndex);
heapSubtree(root, heap.length - 1);
} else if (hasLeftChild) {
heapSubtree(root, heap.length - 1);
}
}
/**
* Gets the root of heap
*
* @return root of heap
*/
private T getRoot(int size) {
swap(heap, 0, size);
heapSubtree(0, size - 1);
// return old root
return heap[size];
}
} }
public <T extends Comparable<T>> T[] sort(T[] unsorted) {
/** return sort(Arrays.asList(unsorted)).toArray(unsorted);
* 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 < heap.length;
boolean hasRightChild = rightIndex < heap.length;
if (hasRightChild) {
//if has left and right
makeMinHeap(leftIndex);
makeMinHeap(rightIndex);
heapSubtree(root, heap.length - 1);
} else if (hasLeftChild) {
heapSubtree(root, heap.length - 1);
}
} }
/** private <T extends Comparable<T>> List<T> sort(List<T> unsorted) {
* Gets the root of heap int size = unsorted.size();
*
* @return root of heap @SuppressWarnings("unchecked")
*/ Heap<T> heap = new Heap<>(unsorted.toArray((T[]) new Comparable[unsorted.size()]));
private T getRoot(int size) {
swap(heap, 0, size); // make min heap using index 0 as root.
heapSubtree(0, size - 1); heap.makeMinHeap(0);
// return old root List<T> sorted = new ArrayList<>(size);
return heap[size]; while (size > 0) {
T min = heap.getRoot(--size);
sorted.add(min);
}
return sorted;
} }
}
public <T extends Comparable<T>> T[] sort(T[] unsorted) {
return sort(Arrays.asList(unsorted)).toArray(unsorted);
}
private <T extends Comparable<T>> List<T> sort(List<T> unsorted) {
int size = unsorted.size();
@SuppressWarnings("unchecked")
Heap<T> heap = new Heap<>(unsorted.toArray((T[]) new Comparable[unsorted.size()]));
// make min heap using index 0 as root.
heap.makeMinHeap(0);
List<T> sorted = new ArrayList<>(size);
while (size > 0) {
T min = heap.getRoot(--size);
sorted.add(min);
}
return sorted;
}
} }

View File

@ -2,74 +2,74 @@ package src.main.java.com.sorts;
public class MergeSort { public class MergeSort {
/** /**
* This method implements the Generic Merge Sort * This method implements the Generic Merge Sort
* *
* @param unsorted the array which should be sorted * @param unsorted the array which should be sorted
* @param <T> Comparable class * @param <T> Comparable class
* @return sorted array * @return sorted array
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends Comparable<T>> T[] sort(T[] unsorted) { public <T extends Comparable<T>> T[] sort(T[] unsorted) {
T[] tmp = (T[]) new Comparable[unsorted.length]; T[] tmp = (T[]) new Comparable[unsorted.length];
doSort(unsorted, tmp, 0, unsorted.length - 1); doSort(unsorted, tmp, 0, unsorted.length - 1);
return unsorted; return unsorted;
}
/**
* @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
**/
private static <T extends Comparable<T>> void doSort(T[] arr, T[] temp, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
doSort(arr, temp, left, mid);
doSort(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
**/
private static <T extends Comparable<T>> void merge(T[] arr, T[] temp, int left, int mid, int right) {
System.arraycopy(arr, left, temp, left, right - left + 1);
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]; * @param arr The array to be sorted
i++; * @param temp The copy of the actual array
k++; * @param left The first index of the array
* @param right The last index of the array
* Recursively sorts the array in increasing order
**/
private static <T extends Comparable<T>> void doSort(T[] arr, T[] temp, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
doSort(arr, temp, left, mid);
doSort(arr, temp, mid + 1, right);
merge(arr, temp, left, mid, right);
}
} }
while (j <= right) { /**
arr[k] = temp[j]; * This method implements the merge step of the merge sort
j++; *
k++; * @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
**/
private static <T extends Comparable<T>> void merge(T[] arr, T[] temp, int left, int mid, int right) {
System.arraycopy(arr, left, temp, left, right - left + 1);
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++;
}
while (j <= right) {
arr[k] = temp[j];
j++;
k++;
}
} }
}
} }

View File

@ -5,61 +5,60 @@ import static src.main.java.com.sorts.SortUtils.swap;
public class QuickSort { public class QuickSort {
/**
/** * This method implements the Generic Quick Sort
* This method implements the Generic Quick Sort *
* * @param array The array to be sorted
* @param array The array to be sorted * Sorts the array in increasing order
* Sorts the array in increasing order **/
**/ public <T extends Comparable<T>> T[] sort(T[] array) {
public <T extends Comparable<T>> T[] sort(T[] array) { doSort(array, 0, array.length - 1);
doSort(array, 0, array.length - 1); return array;
return array;
}
/**
* The sorting process
*
* @param left The first index of an array
* @param right The last index of an array
* @param array The array to be sorted
**/
private static <T extends Comparable<T>> void doSort(T[] array, int left, int right) {
if (left < right) {
int pivot = partition(array, left, right);
doSort(array, left, pivot - 1);
doSort(array, pivot, right);
} }
}
/**
* This method finds the partition index for an array
*
* @param array The array to be sorted
* @param left The first index of an array
* @param right The last index of an array
* Finds the partition index of an array
**/
private static <T extends Comparable<T>> int partition(T[] array, int left, int right) { /**
int mid = (left + right) / 2; * The sorting process
T pivot = array[mid]; *
* @param left The first index of an array
* @param right The last index of an array
* @param array The array to be sorted
**/
while (left <= right) { private static <T extends Comparable<T>> void doSort(T[] array, int left, int right) {
while (less(array[left], pivot)) { if (left < right) {
++left; int pivot = partition(array, left, right);
} doSort(array, left, pivot - 1);
while (less(pivot, array[right])) { doSort(array, pivot, right);
--right; }
} }
if (left <= right) {
swap(array, left, right); /**
++left; * This method finds the partition index for an array
--right; *
} * @param array The array to be sorted
* @param left The first index of an array
* @param right The last index of an array
* Finds the partition index of an array
**/
private static <T extends Comparable<T>> int partition(T[] array, int left, int right) {
int mid = (left + right) / 2;
T pivot = array[mid];
while (left <= right) {
while (less(array[left], pivot)) {
++left;
}
while (less(pivot, array[right])) {
--right;
}
if (left <= right) {
swap(array, left, right);
++left;
--right;
}
}
return left;
} }
return left;
}
} }

View File

@ -5,28 +5,28 @@ import static src.main.java.com.sorts.SortUtils.swap;
public class SelectionSort { public class SelectionSort {
/** /**
* This method implements the Generic Selection Sort * This method implements the Generic Selection Sort
* *
* @param arr The array to be sorted * @param arr The array to be sorted
* Sorts the array in increasing order * Sorts the array in increasing order
**/ **/
public <T extends Comparable<T>> T[] sort(T[] arr) { public <T extends Comparable<T>> T[] sort(T[] arr) {
int n = arr.length; int n = arr.length;
for (int i = 0; i < n - 1; i++) { for (int i = 0; i < n - 1; i++) {
// Initial index of min // Initial index of min
int min = i; int min = i;
for (int j = i + 1; j < n; j++) { for (int j = i + 1; j < n; j++) {
if (less(arr[j], arr[min])) { if (less(arr[j], arr[min])) {
min = j; min = j;
}
}
// Swapping if index of min is changed
if (min != i) {
swap(arr, i, min);
}
} }
}
// Swapping if index of min is changed
if (min != i) {
swap(arr, i, min);
}
}
return arr; return arr;
} }
} }

View File

@ -5,28 +5,28 @@ import static src.main.java.com.sorts.SortUtils.swap;
public class ShellSort { public class ShellSort {
/** /**
* This method implements Generic Shell Sort. * This method implements Generic Shell Sort.
* *
* @param array The array to be sorted * @param array The array to be sorted
*/ */
public <T extends Comparable<T>> T[] sort(T[] array) { public <T extends Comparable<T>> T[] sort(T[] array) {
int length = array.length; int length = array.length;
int n = 1; int n = 1;
while (n < length / 3) { while (n < length / 3) {
n = 3 * n + 1; n = 3 * n + 1;
}
while (n >= 1) {
for (int i = n; i < length; i++) {
for (int j = i; j >= n && less(array[j], array[j - n]); j -= n) {
swap(array, j, j - n);
} }
}
n /= 3;
}
return array; while (n >= 1) {
} for (int i = n; i < length; i++) {
for (int j = i; j >= n && less(array[j], array[j - n]); j -= n) {
swap(array, j, j - n);
}
}
n /= 3;
}
return array;
}
} }

View File

@ -3,43 +3,43 @@ package src.main.java.com.sorts;
final class SortUtils { final class SortUtils {
/** /**
* Helper method for swapping places in array * Helper method for swapping places in array
* *
* @param array The array which elements we want to swap * @param array The array which elements we want to swap
* @param idx index of the first element * @param idx index of the first element
* @param idy index of the second element * @param idy index of the second element
*/ */
static <T> boolean swap(T[] array, int idx, int idy) { static <T> boolean swap(T[] array, int idx, int idy) {
T swap = array[idx]; T swap = array[idx];
array[idx] = array[idy]; array[idx] = array[idy];
array[idy] = swap; array[idy] = swap;
return true; return true;
} }
/** /**
* This method checks if first element is less then the other element * This method checks if first element is less then the other element
* *
* @param v first element * @param v first element
* @param w second element * @param w second element
* @return true if the first element is less then the second element * @return true if the first element is less then the second element
*/ */
static <T extends Comparable<T>> boolean less(T v, T w) { static <T extends Comparable<T>> boolean less(T v, T w) {
return v.compareTo(w) < 0; return v.compareTo(w) < 0;
} }
/** /**
* Swaps all position from {@param left} to @{@param right} for {@param array} * Swaps all position from {@param left} to @{@param right} for {@param array}
* *
* @param array is an array * @param array is an array
* @param left is a left flip border of the array * @param left is a left flip border of the array
* @param right is a right flip border of the array * @param right is a right flip border of the array
*/ */
static <T extends Comparable<T>> void flip(T[] array, int left, int right) { static <T extends Comparable<T>> void flip(T[] array, int left, int right) {
while (left <= right) { while (left <= right) {
swap(array, left++, right--); swap(array, left++, right--);
}
} }
}
} }

View File

@ -5,35 +5,35 @@ import static src.main.java.com.sorts.SortUtils.less;
public class StoogeSort { public class StoogeSort {
/** /**
* This method implements recursion StoogeSort * This method implements recursion StoogeSort
* *
* @param int[] array to store number elements * @param arr array to store number elements
* @param f first element in the array * @param f first element in the array
* @param l last element in the array * @param l last element in the array
*/ */
public <T extends Comparable<T>> T[] sort(T[] arr, int f, int l) { public <T extends Comparable<T>> T[] sort(T[] arr, int f, int l) {
// Ends recursion when met // Ends recursion when met
if (f >= l) if (f >= l)
return arr; return arr;
if (less(arr[l], arr[f])) { if (less(arr[l], arr[f])) {
swap(arr, f, l); swap(arr, f, l);
} }
if (l - f + 1 > 2) { if (l - f + 1 > 2) {
int entry = (l - f + 1) / 3; int entry = (l - f + 1) / 3;
// Does a recursive sort of the first two thirds elements // Does a recursive sort of the first two thirds elements
sort(arr, f, l - entry); sort(arr, f, l - entry);
// Does a recursive sort of the last two thirds elements // Does a recursive sort of the last two thirds elements
sort(arr, f + entry, l); sort(arr, f + entry, l);
// Another recursive sort first two thirds elements to confirm // Another recursive sort first two thirds elements to confirm
sort(arr, f, l - entry); sort(arr, f, l - entry);
} }
return arr; return arr;
} }
} }

View File

@ -3,5 +3,5 @@ package src.main.java.com.types;
@FunctionalInterface @FunctionalInterface
public interface Sort<T> { public interface Sort<T> {
public <T extends Comparable<T>> T[] sort(T[] array); <T extends Comparable<T>> T[] sort(T[] array);
} }

View File

@ -1,30 +1,29 @@
package src.main.java.com.dataStructures; package src.test.java.com.dataStructures;
import org.junit.Test; import org.junit.Test;
import src.main.java.com.dataStructures.BinaryTree;
import static org.junit.Assert.*; import static org.junit.Assert.*;
/**
*
* @author RICARDO
*/
public class BinaryTreeTest { public class BinaryTreeTest {
public BinaryTreeTest() { public BinaryTreeTest() {
} }
/** /**
* Test of insert method, of class BinaryTree. * Test of insert method, of class BinaryTree.
*/ */
@Test @Test
public void testInsert_BinaryTree() { public void testInsertBinaryTree() {
System.out.println("insert"); System.out.println("insert");
BinaryTree<String> lowerdata = new BinaryTree<>("1"); BinaryTree<String> lowerData = new BinaryTree<>("1");
BinaryTree<String> upperdata = new BinaryTree<>("3"); BinaryTree<String> upperData = new BinaryTree<>("3");
BinaryTree<String> instance = new BinaryTree<>("2"); BinaryTree<String> instance = new BinaryTree<>("2");
instance.insert(lowerdata); instance.insert(lowerData);
instance.insert(upperdata); instance.insert(upperData);
String proof = instance.getLeft().toString()+instance.toString()+instance.getRight().toString(); String proof = instance.getLeft().toString()
System.out.println(proof); + instance.toString()
+ instance.getRight().toString();
assertEquals("123", proof); assertEquals("123", proof);
} }
@ -36,10 +35,10 @@ public class BinaryTreeTest {
System.out.println("search"); System.out.println("search");
BinaryTree<Integer> instance = new BinaryTree<>(5); BinaryTree<Integer> instance = new BinaryTree<>(5);
for (int i = 1; i < 10; i++) { for (int i = 1; i < 10; i++) {
instance.insert(new Integer(i)); instance.insert(i);
} }
BinaryTree result = instance.search(new Integer(1)); BinaryTree result = instance.search(1);
assertEquals(new Integer(1), result.getData()); assertEquals(1, result.getData());
} }
/** /**
@ -52,9 +51,8 @@ public class BinaryTreeTest {
for (int i = 1; i < 10; i++) { for (int i = 1; i < 10; i++) {
instance.insert(i); instance.insert(i);
} }
boolean result = instance.contains(2)&&instance.contains(11);
assertEquals(false, result);
}
boolean result = instance.contains(2) && instance.contains(11);
assertFalse(result);
}
} }