Friday, March 18, 2016

Sorting: Merge Sort

Sorting is a combination of algorithms or instructions that you give in Java for the program to organize an array of numbers either from smallest to biggest or from biggest to smallest, this helps for your computer to more easily and quickly run a program which has to find a specific number. There are several ways to sort in Java there are Selection, Merge, and Insertion Sorts and each are differently efficient and are used for different reasons.

Merge Sort
Algorithm:
public class MyMergeSort {
     
    private int[] array;
    private int[] tempMergArr;
    private int length;
 
    public static void main(String a[]){
         
        int[] inputArr = {45,23,11,89,77,98,4,28,65,43};
        MyMergeSort mms = new MyMergeSort();
        mms.sort(inputArr);
        for(int i:inputArr){
            System.out.print(i);
            System.out.print(" ");
        }
    }
     
    public void sort(int inputArr[]) {
        this.array = inputArr;
        this.length = inputArr.length;
        this.tempMergArr = new int[length];
        doMergeSort(0, length - 1);
    }
 
    private void doMergeSort(int lowerIndex, int higherIndex) {
         
        if (lowerIndex < higherIndex) {
            int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
            // Below step sorts the left side of the array
            doMergeSort(lowerIndex, middle);
            // Below step sorts the right side of the array
            doMergeSort(middle + 1, higherIndex);
            // Now merge both sides
            mergeParts(lowerIndex, middle, higherIndex);
        }
    }
 
    private void mergeParts(int lowerIndex, int middle, int higherIndex) {
 
        for (int i = lowerIndex; i <= higherIndex; i++) {
            tempMergArr[i] = array[i];
        }
        int i = lowerIndex;
        int j = middle + 1;
        int k = lowerIndex;
        while (i <= middle && j <= higherIndex) {
            if (tempMergArr[i] <= tempMergArr[j]) {
                array[k] = tempMergArr[i];
                i++;
            else {
                array[k] = tempMergArr[j];
                j++;
            }
            k++;
        }
        while (i <= middle) {
            array[k] = tempMergArr[i];
            k++;
            i++;
        }
 
    }
}

There are different reasons why anyone would use Merge Sort instead of other kinds:
1) it is the most efficient type of sorting for bigger arrays of numbers.
2) it offers performance just bellow Quick Sort but uses less memory space.
Merge Sort
Merge Sort Demo.
However it takes more knowledge of coding and a greater understanding of algorithms, and it takes a considerable amount of memory space, if used frequently.

Friday, March 11, 2016

Abstract and Interfaces.

There are ways to assist with inheritance and polymorphism which is done by abstract classes and interfaces these kinds of java files are used for different reasons. They both have abstract methods and those methods cannot be described like normal methods and have to be implemented in any child class of the abstract class and implemented classes.
public interface AnInteface{ // This is how to create an interface.
  public void aMathod(); // This is the way to instaciate an abstract method.
public abstract class AnAbstractClass{ // This is how to create an abstract class.
  public abstract void aMethod(); //This is another way to write an abstract method but abstract 
  // classes can also implement non-abstract methods.
 public String aString(){
  String a = "A string";
  return a;
 }
}
There are two ways to implement these classes to another class:
public class NormalClass extends AnAbstractClass implements AnInterface{
 public void AMethod(){
 }// You have to incorporate the same abstract methods in a class that implements the interface or          // extends the abstract class 
}

Friday, March 4, 2016

Encapsulation and Polymorphism

Encapsulation is a term in Java programming and in general programming that refers to the privatization of files for classes and encapsulation of packages, there are different encapsulation key words: public, private and protected. they all do different things to your variables, classes, or methods. the public word allows to access a class, variable, or methods from one another if they are imported. The private keyword does not allow the interchange of classes, methods or variables even if they are imported. And the protected keyword only allows for methods, classes and variables to be used only within the same package. The way to import packages in any IDE from one class file is the keyword 'import' followed by a space. Ex: import java.util.*; the java.util library imports many very useful classes to the class to which you use this on, such as Random which has methods that create random numbers, or the Scanner class which reads user input from the console and gives it to a variable.
Plymorphism is a way to import classes in Java and assign them to another class as a child of that class, the best way to understand this is - Imagine that you have a dog, well that dog is an animal, but not all animals are dogs. In Java the way to assign an object as a sub-variable of another object is polimorphism.
the way to do that is to use the extends keyword it is used like this:
public class Cats extends Animals()
// all of the public methods from Animals will be usable in the Cats class.

Friday, February 26, 2016

System.out.print("Strings");

Strings are identifiers that are composed of one or many char identifiers, they can hold a big amount of characters and can be modified within a program in an amount of ways. a usual string is created in this way: String str1 = "Hello World";   It is very important that String is capitalized, that it's variable is stated with a quotation mark for both starting and beginning the string and that it ends with a semicolon.
Print method.
The print method is a method from the java.util.Object class in java that is the main class from which you import statements and methods from. It allows you to use String, String manipulation methods, the Print methods, and other equally important methods.
The print method is stated like this:
System.out.print("This is a print");
This will print the words "This is a print" to console. This is often used outside of the Graphic interfaces of programs for debugging purposes.
There are different methods that are used to manipulate String objects: charAt(), substring(), contains(), indexOf(), concat(), equals(), length(), trim(), etc.
These are used for different purposes, charAt(int) will find a char type data at a certain index from the string on which is used, it has parameters of int which means that you need to introduce an int and it will find the character from that position.
The method substring(int, int) requires two integers one for the beginning of the sub string and one for the end, it will take a chunk from between the two given indexes.
The method contains(String) has a String parameter and will find if the string it's used on has a sub string with the exact composition of the parameter string and will give it back as a boolean.
To find an index of a sub-string or a char then you use the indexOf(String) method which will return an int.
The method concat(String) allows you to concatenate two strings together, it will add the parameter string into the string to which the method is used.
equals(String) is the most secure way to see if two strings are equal to each other instead of using the == identifier.
length() will return an int with the number of characters that are in a single string variable.
trim() will erase from a string any excess white space from before or after a string.
REMEMBER: every time you modify a String object the String class does not dump the previous object instead it creates a new one and saves the other one.

String a = "\'a small fox sleeps\'"; if(a.contains("fox")){System.out.print(a);}
This will print: 'a small fox sleeps' to the console.

Apart from manipulating Strings with those three methods it is also possible to turn other primitive data to Strings. The method toString() from the class of any primitive data will turn it to Strings:
Integer.toString(), Double.toString(), Boolean.toString(), etc.

Friday, February 12, 2016

Loops.

The while and for loops are the most important types of loops, and the most commonly used, there is also an advanced for loop called the for each loop but arrays are needed for it.
The while loop is a loop that keeps doing the code inside it until it's conditional is false.

boolean end = false;
int point = 0;
while(!end){
point ++;
if(point > 10){
end;
}
}
//this will run the loop until points is 10

As well as there being a for loop which runs the loop until the conditional say x < 10 reaches false, but is written differently than the while loop and is more controllable.

int point = 0;
for(int i = 0; i < 10; i++){
point++;
System.out.println(point);
}
//this program will run the loop ten times and will print on the console numbers from 1 to 11
// this is because the value of point is increased before the print statement

Loops are allowed to be inside of each other and you can use multiple combinations of the code to achieve different outcomes.

while(!end){
for(int i = 0; i < 10; i++){
point++;
System.out.print(point);
}
System.out.println();
if(point > 30){
end = true;
}
}
//this will run the loops until point is 30, the for loop will run 30 times and the while loop 3 times

For the next loop you will need to know about arrays, which is another post in this blog. After knowing about arrays you can use the for each loop, which loops for every array object or value.

int[] array = new int[4];
for(int arr : array){
arr = 3;
}
//this sets every int of the array to the number 3
//for-each loops are useful for scrolling around arrays quickly

String[] array = {"This", "is", "an", "array"}

Arrays and matrices are essential in Java programming, and programming in general. they are groups of variables or objects that hold different data in them.
a single array holds as many variables of the same data requirements that you need.

int[] array = new int[7];
int x = 1;
for(int i : array){
 i = x;
x++;
}
//this program will create an array of integers

There are different ways to instantiating an array
String[] names = {"Edward", "Joseph", "Smigla"};
for(String name : names){
System.out.print(name + " ");
}
//this code will print: Edward Joseph Smigla on the console
//you can also pull any variable from an array using the index
names[1] = "E.";
names[1] = "J.";
names[1] = "Shmigs";
for(String name : names){
System.out.print(name + " ");
}//this code will print: E .J. Shmigs on the console
//the index of the arrays is in programmer numbers 0 - 2 for arrays with 3 indexes
//always decreasing the index number by one from the amount of indexes

you can also create arrays of objects such as this:
public Integer[] array = new Integer[32];
for(int i = 0; i < array.length(); i++){
array[i] = (int)(Math.random()*32);
}//Remember to cast because Math.random() give a double //variable
// you do not need to use the for-each loop to cycle through arrays, you can also use the length()
//method, which finds the length of the array given  and returns it

You can also create arrays of arrays which are called matrices or 2D arrays (you can create as many arrays of arrays as needed)

int[][] numbers = new int[5][5];//this will create a 2D array containing 25 int variables
for(int i = 0; i < array.length(); i++){
for(int j = 0; j < array[i].length(); j++){
array[i][j] = (int)(Math.random() * 25);
System.out.print(array[i][j] + " ");
}
System.out.println();
}//to give values to multiple index arrays you need multiple loops
//this will print random values from 0 - 24, 25 times (with a space in between and a new line every //five variables)

Matrices can be instantiated in different ways like the simple array.

int[][] numbers = {{1,2,3},{4,5,6},{7,8,9}};
//this instantiates a 2D array with the variables 1,2,3,4,5,6,7,8, and 9. in different levels of the array

Monday, February 8, 2016

If, Else Statements, and Switch.

If are ways to chose conditionals this can relate directly into real life, for example the problem about milk and eggs, when you go to the store and want to buy milk and eggs you first have to know whether there are milk and eggs. This problem in code would be solved with conditional statements:
int milk = 0;
boolean eggs = true;
if (eggs){
milk = 6;
}
//That indicates what the programmer in the picture thought of //when going to the store
else{
milk = 1;
}
After this you have to make up an alternative to your condition just to make sure that if the condition is false then you are able to get a controlled result this is achieved with an else statement, for the else statement you do not need a condition because one was already stated, however you can use another if statement to add a condition.
int milk = 0;
int eggs = 20;
if (eggs > 0){
milk = 6;
}else if (eggs < 0){
milk = 1;
}
//This will identify that if there is more than 0 eggs there will be 6 bottles of milk, however if there is //no eggs the you'll only buy 1 bottle of milk.
Switch statements help identify different conditionals.
int milk = (int)(Math.random() * 6);//Will randomize the amount of milk from 0-6, remember casting
int eggs;
switch(milk){
case 1: eggs = 1;
          break;
case 2: eggs = 2;
          break;
case 3: eggs = 3;

default : eggs = 4;
          break;
}
This conditional will check the value of milk and will compare it to the different cases that it's given, which will help indicate what block of code to activate, the "break" statement helps finishing the statement, without it the program would do the cases under the one without break until finding a break or a default statement, for example in the case 3 it would assign eggs to the value of 3, but then it would do the default case which assign eggs to 4.