# Java Algorithms

Welcome to my Java Algorithms tutorial. In this series I will cover everything there is to know about Java algorithms and data structures.

An algorithm is just the steps you take to manipulate data. A data structure is the way data is arranged in memory. There are 3 main data structure operations I will focus on first being inserting, deleting and searching for data.

Like all of my tutorials, everything is simple at first and then I cover more complex topics. The code below should help.

If you like videos like this, it helps to tell Google+

Code From the Video

ArrayStructures.java

```public class ArrayStructures {

private int[] theArray = new int[50]; // Creates an array with 50 indexes

private int arraySize = 10; // Elements in theArray

// Fills the Array with random values

public void generateRandomArray(){

for(int i = 0; i < arraySize; i++){

// Random number 10 through 19

theArray[i] = (int)(Math.random()*10)+10;

}

}

public int[] getTheArray(){

return theArray;

}

public int getArraySize(){

return arraySize;

}

// Prints the Array on the screen in a grid

public void printArray(){

System.out.println("----------");

for(int i = 0; i < arraySize; i++){

System.out.print("| " + i + " | ");

System.out.println(theArray[i] + " |");

System.out.println("----------");

}

}

// Gets value at provided index

public int getValueAtIndex(int index){

if(index < arraySize) return theArray[index];

return 0;

}

// Returns true or false if a value is in the Array

public boolean doesArrayContainThisValue(int searchValue){

boolean valueInArray = false;

for(int i = 0; i < arraySize; i++){

if(theArray[i] == searchValue){

valueInArray = true;

}

}

return valueInArray;

}

// Delete Array row for the index and move elements up

public void deleteIndex(int index){

if(index < arraySize){

// Overwrite the value for the supplied index
// and then keep overwriting every index that follows
// until you get to the last index in the array

for(int i = index; i < (arraySize - 1); i++){

theArray[i] = theArray[i+1];

}

arraySize--;

}

}

public void insertValue(int value){

if(arraySize < 50){

theArray[arraySize] = value;

arraySize++;

}

}

// Linear Search : Every index must be looked at

public String linearSearchForValue(int value){

boolean valueInArray = false;

String indexsWithValue = "";

System.out.print("The Value was Found in the Following Indexes: ");

for(int i = 0; i < arraySize; i++){

if(theArray[i] == value) {
valueInArray = true;

System.out.print(i + " ");

indexsWithValue+= i + " ";
}

}

if(!valueInArray){
indexsWithValue = "None";

System.out.print(indexsWithValue);
}

System.out.println();

return indexsWithValue;

}

// This bubble sort will sort everything from
// smallest to largest

public void bubbleSort(){

// i starts at the end of the Array
// As it is decremented all indexes greater
// then it are sorted

for(int i = arraySize - 1; i > 1; i--){

// The inner loop starts at the beginning of
// the array and compares each value next to each
// other. If the value is greater then they are
// swapped

for(int j = 0; j < i; j++){

if(theArray[j] > theArray[j + 1]){

swapValues(j, j+1);

}

}

}

}

public static void main(String[] args){

ArrayStructures newArray = new ArrayStructures();

newArray.generateRandomArray();

newArray.printArray();

System.out.println(newArray.getValueAtIndex(3));

System.out.println(newArray.doesArrayContainThisValue(18));

newArray.deleteIndex(4);

newArray.printArray();

newArray.insertValue(55);

newArray.printArray();

newArray.linearSearchForValue(17);
}

}```

Β The MVC Version of the Above Program

```public class ArrayStructure {

private int[] theArray = new int[50]; // Creates an array with 50 indexes

private int arraySize = 10; // Elements in theArray

// Fills the Array with random values

public void generateRandomArray(){

for(int i = 0; i < arraySize; i++){

theArray[i] = (int)(Math.random()*9)+10;

}

}

public int[] getTheArray(){

return theArray;

}

public int getArraySize(){

return arraySize;

}

// Used to slow down calculations

public void pauseAndUpdate(){

try {
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

// Prints the Array on the screen in a grid

public void printArray(){

System.out.println("----------");

for(int i = 0; i < arraySize; i++){

System.out.print("| " + i + " | ");

System.out.println(theArray[i] + " |");

System.out.println("----------");

}

}

// Gets value at provided index

public int getValueAtIndex(int index){

if(index < arraySize) return theArray[index];

return 0;

}

// Returns true or false if a value is in the Array

public boolean doesArrayContainThisValue(int searchValue){

boolean valueInArray = false;

for(int i = 0; i < arraySize; i++){

if(theArray[i] == searchValue){

valueInArray = true;

}

}

return valueInArray;

}

// Delete Array row for the index and move elements up

public void deleteIndex(int index){

if(index < arraySize){

// Overwrite the value for the supplied index
// and then keep overwriting every index that follows
// until you get to the last index in the array

for(int i = index; i < (arraySize - 1); i++){

pauseAndUpdate();

theArray[i] = theArray[i+1];

}

arraySize--;

}

}

public void insertValue(int value){

if(arraySize < 50){

pauseAndUpdate();

theArray[arraySize] = value;

arraySize++;

}

}

// Linear Search : Every index must be looked at

public String linearSearchForValue(int value){

boolean valueInArray = false;

String indexsWithValue = "";

System.out.print("The Value was Found in the Following Indexes: ");

for(int i = 0; i < arraySize; i++){

if(theArray[i] == value) {
valueInArray = true;

System.out.print(i + " ");

indexsWithValue+= i + " ";
}

}

if(!valueInArray){
indexsWithValue = "None";

System.out.print(indexsWithValue);
}

System.out.println();

return indexsWithValue;

}

// This bubble sort will sort everything from
// smallest to largest

public void bubbleSort(){

// i starts at the end of the Array
// As it is decremented all indexes greater
// then it are sorted

for(int i = arraySize - 1; i > 1; i--){

// The inner loop starts at the beginning of
// the array and compares each value next to each
// other. If the value is greater then they are
// swapped

for(int j = 0; j < i; j++){

if(theArray[j] > theArray[j + 1]){

swapValues(j, j+1);

}

}

}

}

// This bubble sort will sort everything from
// largest to smallest

public void bubbleSortDescending(){

// i starts at the beginning of the array

for(int i = 0; i < arraySize; i++){

// The inner loop starts at the beginning of
// the array 1 index in more than i.

for(int j = 1; j < (arraySize - i); j++){

// Here we check if the 1st index is less
// than the next during the first run through
// Then we just increase the indexes until
// they have all been checked

if(theArray[j-1] < theArray[j]){

swapValues(j-1, j);

}

}

}

}

public void swapValues(int indexOne, int indexTwo){

int temp = theArray[indexOne];
theArray[indexOne] = theArray[indexTwo];
theArray[indexTwo] = temp;

}

// The Binary Search is quicker than the linear search
// because all the values are sorted. Because everything
// is sorted once you get to a number larger than what
// you are looking for you can stop the search. Also
// you be able to start searching from the middle
// which speeds the search. It also works best when
// there are no duplicates

public void binarySearchForValue(int value){

int lowIndex = 0;
int highIndex = arraySize - 1;

while(lowIndex <= highIndex){

int middleIndex = (highIndex + lowIndex) / 2;

if(theArray[middleIndex] < value) lowIndex = middleIndex + 1;

else if(theArray[middleIndex] > value) highIndex = middleIndex - 1;

else {

System.out.println("Found a Match for " + value + " at Index " + middleIndex);

lowIndex = highIndex + 1;

}

}

}

public static void main(String[] args){

/*

ArrayStructure newArray = new ArrayStructure();

newArray.generateRandomArray();

newArray.printArray();

System.out.println(newArray.getValueAtIndex(9));

System.out.println(newArray.doesArrayContainThisValue(11));

newArray.deleteIndex(3);

newArray.insertValue(100);

newArray.bubbleSort();

newArray.printArray();

newArray.linearSearchForValue(11);

newArray.binarySearchForValue(12);

newArray.bubbleSortDescending();

newArray.printArray();

*/

}

}```

```import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;

import java.awt.Font;
import java.awt.event.*;

public class JavaAlgorithms extends JFrame {

private JPanel contentPane;

private JTextField arrayValueTextField;
private JTable table;
private JTextField arrayIndexTextField;
private JButton insertButton, deleteButton, findButton, sortButton;

int cellToMark = -1;

// Holds the array that goes in JTable

Object[][] data = {
{new Integer(0), new Integer(0), ""},
{new Integer(1), new Integer(0), ""},
{new Integer(2), new Integer(0), ""},
{new Integer(3), new Integer(0), ""},
{new Integer(4), new Integer(0), ""},
{new Integer(5), new Integer(0), ""},
{new Integer(6), new Integer(0), ""},
{new Integer(7), new Integer(0), ""},
{new Integer(8), new Integer(0), ""},
{new Integer(9), new Integer(0), ""},
};

String[] columnNames = {"Index",
"Value",
"Selected"};

DefaultTableModel dTableModel = new DefaultTableModel(data, columnNames);

/**
* Create the frame.
*/
public JavaAlgorithms() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 970, 800);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);

JLabel valueLabel = new JLabel("Value");
valueLabel.setFont(new Font("Dialog", Font.BOLD, 30));

arrayValueTextField = new JTextField();
arrayValueTextField.setFont(new Font("Dialog", Font.PLAIN, 30));
arrayValueTextField.setColumns(10);

JLabel indexLabel = new JLabel("Index");
indexLabel.setFont(new Font("Dialog", Font.BOLD, 30));

arrayIndexTextField = new JTextField();
arrayIndexTextField.setFont(new Font("Dialog", Font.PLAIN, 30));
arrayIndexTextField.setColumns(10);

insertButton = new JButton("Insert");
insertButton.setFont(new Font("Dialog", Font.BOLD, 30));

deleteButton = new JButton("Delete");
deleteButton.setFont(new Font("Dialog", Font.BOLD, 30));

findButton = new JButton("Find");
findButton.setFont(new Font("Dialog", Font.BOLD, 30));

JScrollPane scrollPane = new JScrollPane();

// Stores the radio buttons so when one is selected the other is deselected

ButtonGroup sortDirection = new ButtonGroup();

sortButton = new JButton("Sort");
sortButton.setFont(new Font("Dialog", Font.BOLD, 30));

// Sets up the radio buttons for the search type

ButtonGroup searchType = new ButtonGroup();

JTextArea textArea = new JTextArea("Output");
textArea.setFont(new Font("Dialog", Font.PLAIN, 30));

// ------------------------

GroupLayout groupLayout = new GroupLayout(contentPane);

groupLayout.setHorizontalGroup(
);
groupLayout.setVerticalGroup(
);

table = new JTable(dTableModel);

// Set the font for the table column titles

// Set the font for the data in the columns

table.setFont(new Font("Dialog", Font.BOLD, 30));

// Increase the row height so that the larger font fits

table.setRowHeight(table.getRowHeight()+30);

scrollPane.setViewportView(table);

contentPane.setLayout(groupLayout);
}

// Set up all the listeners

}

}

}

}

// Other Random Methods Needed

void sendMessageToUser(String errorMessage){

JOptionPane.showMessageDialog(this, errorMessage);

}

public int getTheValue(){

return Integer.parseInt(arrayValueTextField.getText());

}

public int getTheIndex(){

return Integer.parseInt(arrayIndexTextField.getText());

}

public void updateTheTable(int[] newArray, int rows){

Object[] tempRow;

dTableModel.setRowCount(0); // Clear JTable

for(int i = 0; i < rows; i++){

if(i == this.cellToMark)tempRow = new Object[]{i, newArray[i], "XXXXX"};

else tempRow = new Object[]{i, newArray[i], ""};

}

}

}

class AlgorithmsMVC{

public static void main(String[] args) {

JavaAlgorithms theView = new JavaAlgorithms();
ArrayStructure theModel = new ArrayStructure();

AlgorithmsController theController = new AlgorithmsController(theView, theModel);

theView.setVisible(true);

}

}

class AlgorithmsController{

private JavaAlgorithms theView;
private ArrayStructure theModel;

public AlgorithmsController(JavaAlgorithms theView, ArrayStructure theModel){

this.theView = theView;
this.theModel = theModel;

theModel.generateRandomArray();

// Put random array data in the table model

theView.updateTheTable(theModel.getTheArray(), theModel.getArraySize());

}

// ActionListener for the Insert Button

class InsertButtonListener implements ActionListener{

public void actionPerformed(ActionEvent arg0) {

try{

theModel.insertValue(theView.getTheValue());

// Take the array data from the model & move it to the JTable

theView.updateTheTable(theModel.getTheArray(), theModel.getArraySize());

}

catch(NumberFormatException ex){

theView.sendMessageToUser("You Need a Value in the Value Box");

}

}

}

// ActionListener for the Insert Button

class DeleteButtonListener implements ActionListener{

public void actionPerformed(ActionEvent arg0) {

try{

theModel.deleteIndex(theView.getTheIndex());

theView.updateTheTable(theModel.getTheArray(), theModel.getArraySize());

}

catch(NumberFormatException ex){

theView.sendMessageToUser("You Need a Index in the Index Box");

}

}

}

// ActionListener for the Find Button

class FindButtonListener implements ActionListener{

public void actionPerformed(ActionEvent arg0) {

String indexWithValue = "";

try{

indexWithValue = theModel.linearSearchForValue(theView.getTheValue());

}

theView.sendMessageToUser("Found in Index: " + indexWithValue);

}

catch(NumberFormatException ex){

theView.sendMessageToUser("You Need a Value in the Value Box");

}

}

}

// ActionListener for the Sort Button

class SortButtonListener implements ActionListener{

public void actionPerformed(ActionEvent arg0) {

try{

theModel.bubbleSort();

} else {

theModel.bubbleSortDescending();

}

theView.updateTheTable(theModel.getTheArray(), theModel.getArraySize());

}

catch(NumberFormatException ex){

theView.sendMessageToUser("Something Went Wrong");

}

}

}

}
```

### 57 Responses to “Java Algorithms”

1. Hasan says:

You are too fast :/ please teach slowly π

• Derek Banas says:

Sorry about that. It may help to print the code and take notes. I tend to be quicker then everyone else

2. Guray says:

About 950 lines of high quality and free code, and this is just for one of your hundreds videos.
You are the Man !

• Derek Banas says:

Thank you very much π Everything I ever do will be free. Always feel free to do anything you’d like with the code

• Random_Guy says:

Hey Buddy,

Have you ever thought of making teams for such a great free work you do?

• Derek Banas says:

Hey, I’m not sure what you mean by teams? Thank you π I’m glad you enjoy the videos.

3. Aamir says:

hi derek, i just understood some 400 lines of code from this video which should take a college teacher a week to teach, u r so quick and this is the thing i like about u. be quick and fast and upload as many videos on java as u can.i am hoping that u will make videos on android development.thanks a lot man.

• Derek Banas says:

Thank you very much π I do my best. Sorry it took so long to answer you. My real life world has been a little out of control lately

4. Aamir says:

derek the above MVC code is complicated, it took me half an hour to figure it out. i think AlgorithmsMVC should be declared as public class in his own source file because it is the class that contains main method

• Derek Banas says:

Sorry about that. AlgorithmsMVC is actually protected here and all the other classes can access it because they are in the same package. It could have been public, but that isn’t needed. Does that make sense?

5. Aamir says:

hi derek, i wrote some two or three commnets but all of them are deleted i don’t know what is happening.plz explain.

• Derek Banas says:

Sorry about that. I got backed up because my real world life has been crazy

6. AAMIR says:

hi derek, i wanna say is that i posted two comments 2 days ago and both of them r deleted.did i do something wrong that i deleted them if u did not then plz look into the matter i am waiting for ur response.

7. Arash Saidi says:

Derek, you are simply an amazing human being. You have made hundreds of videos, thousands of lines of code, and all for free, to teach us mere mortals. That’s beyond inspiring. You make me want to become a better human being!

• Derek Banas says:

Thank you π I just enjoy helping people. It is very gratifying to be able to help. Thank you for the very kind words!

8. Anonymous says:

great job!!

9. James says:

Awesome tutorials, love your tempo, straight to the point and knowledgeable. Personally find I don’t remember much when its s l o w and d u l l lecture type explanations. I will working through all your coding tutorials π Have you been coding for a long time I wonder?

• Derek Banas says:

I have been programming since I was about 10, so I have almost 30 years of experience. I’m glad you like the videos. I always wanted to make original videos, so I figured since everyone else was slow I’d make fast ones

10. zahra says:

Hey derek, i almost gave up on java until i found your tutorials. i just want to thank you for boosting up my confidence. And its so pleasing to see people like you are helping us to get through this tough topics without any cost. you have no idea how you are changing our lives. and my best wishes for you to carry on
π

• Derek Banas says:

Thank you very much for taking the time to say I helped π I have continued to make these tutorials because of all the kind people I have met from around the world.

I originally planned to do my best to provide a free education to all, but I don’t think I would have stuck with it for over 5 years if I wouldn’t have met all the nice people that I have. I’m extremely grateful that I’m able to help.

Thanks again
Derek

Just one question. How did you call non-static functions from a static context. How did you call them in void main?

• Derek Banas says:

I created an object of type newArray. Does that answer your question?

Yes! I was very tired and doing this on 3 am on BlueJ. I’m trying to learn about CS teoretical stuff since I have a degree in economics. I’ve been doing java for about 2 years. I’m actually embarassed by my question. LOL.

Best core java tutorials on youtube!

• Derek Banas says:

Always feel free to ask questions and thank you for the nice compliment π

12. Rohit says:

Excellent tutorial!! Thanks and keep up the good work.

• Derek Banas says:

Thank you very much π Many more videos are coming.

13. Fahir says:

i started viewing ur series about arlgorithms,and i can understand whats going on but i have some troubles i would like u to clear for me, i will go one by and i would like u to explain to me like that, if its not a problem.

1st: when u declared in the beggining theArray = new int[50], does that mean that the array contains 50 int elements, i mean because u puted arraySize to be equal to 10; does that mean even if u put that theArray = new int[10]; instead of 50 it would print the same like it printed with 50, i mean when u do the math.random() stuff

2nd: about the Math.random()*10)+10 , it prints the random number from 10 through 19 thats because of the 0th index in the array right

3rd: in the deleteIndex method in the for loop i < (arraySize – 1) i get that its because the arrays first index is 0 and arraySize is equal to 10 , but what i dont get u said in ur video it because arraySize is 10 and we have 9 fields, how come we have nine fields i mean we have from 0 to 9 thats the count 0, can u explain to me that please, and also u putted theArray[i] = theArray[i + 1]; in for loop if the same method, why did u put theArray[i +1]

4th: in the insertValue method i dont understand why is it if(arraySize < 50) , i get in the other methods if(index < arraySize) etc i understand that, because arraySize is up to 10 and if u put index to be 11 then u will get nothing because u dont have that column, but here i dont get why is it < 50 and in ur video u putet value 55 and it was added, can u please explan to me that. and also in the same method : theArray[arraySize] = value; i dont understand this, if u can also explain to me this.

thank u in advance for all ur hard work and great tutorials!

im still trying to figure out whats going on in the linearSearch and im shure i have question about that one too but i want to get the main idea how it works and then i will ask u about it. π

• Fahir says:

in the 3rd , where i explained about how i dont understand how we have 9 fields i forgot to write 10 where i said that we have from 0 to 9 and thats 10 ,countung the 0th index

• Fahir says:

also i forgot in the insertValue method, why is it theArray[arraySize] = value; can u explain to me exactly what that means

• Derek Banas says:

The current array size is being monitored by the class here

private int arraySize = 10; // Elements in theArray – See more at: http://www.newthinktank.com/2013/02/java-algorithms/#sthash.u4D88pjR.dpuf

Value was either increased or decreased by these methods

public void deleteIndex(int index){
086
087 if(index < arraySize){ 088 089 // Overwrite the value for the supplied index 090 // and then keep overwriting every index that follows 091 // until you get to the last index in the array 092 093 for(int i = index; i < (arraySize - 1); i++){ 094 095 theArray[i] = theArray[i+1]; 096 097 } 098 099 arraySize--; 100 101 } 102 103 } 104 105 public void insertValue(int value){ 106 107 if(arraySize < 50){ 108 109 theArray[arraySize] = value; 110 111 arraySize++; 112 113 } 114 115 } - See more at: http://www.newthinktank.com/2013/02/java-algorithms/#sthash.u4D88pjR.dpuf

• Fahir says:

also in the linear search method im confused at the end where it says if(!valueInArray) does this mean if valueInArray is not false because u puted it to be false in the begining and also if i was true in the begining than it would mean if valueInArray is not true , am i right, if not can u explan to me please thank you

• Fahir says:

i think i figured it out about the if(!valueInArray), i think its not refereing to the valueInArray in the top its refering to the valueInArray in the if loop which is in the for loop, and it means if valueInArray is not true ,because in the if statement valueInArray is set to true, in that case indexsWithValue are none, because the valueInArray is not true and system prints none because there are no values in indexes, am i right this time π

• Derek Banas says:

valueInArray is just a way for us to mark that the value is in the array or not. It is either set to true while checking in the following code or it remains false. Sorry about the confusion.

for(int i = 0; i < arraySize; i++){ 128 129 if(theArray[i] == value) { 130 valueInArray = true; 131 132 System.out.print(i + " "); 133 134 indexsWithValue+= i + " "; 135 } 136 137 } - See more at: http://www.newthinktank.com/2013/02/java-algorithms/#sthash.u4D88pjR.dpuf

• Derek Banas says:

int[50] means that that is the maximum number of items in the array since it is static. arraySize monitors how many items are currently in the array.

Math.random()*10 : Generates numbers between 0 and 9

I’m sorry, but I don’t understand the 3rd question.

I’m checking to make sure I don’t try and add more values then the array allows with i < (arraySize β 1) I hope that helps π

14. Jason says:

Perfect! Finally tutorials that are comprehensive and intelligently presented. Thanks a million for these!

15. stuff says:

Thank you sir!

16. Alsulami says:

Hi Derek Banas;
thank you for spending your time to help people. If you have time, I’d like you to teach me in Data Structure.
again many thanks for your help.

• Derek Banas says:

Hi, You are very welcome. What data structure do you want me to cover?

• Alsulami says:

The book is (Data Structures Abstraction and Design Using Java) and I also would like to discuss this via email if it’s possible.
Many thanks for you

• Derek Banas says:

Sorry, but I have not read that book. I plan on getting back into data structures and algorithms soon though. Feel free to leave any questions you have here. I get over 1000 emails a day.

17. Abhishek says:

Hi Derek, Can you post a video, detailing the Dijkstra’s algorithm.

Thanks
Abhishek

18. Yavar says:

19. Phoebe Resnik says:

Hi Derek!
Your tutorials are so awesome, I can’t thank you enough!!!
Will you be covering iOS development anytime soon?
Thank you so much for your wonderful work, it’s helped me so much.

• Derek Banas says:

Thank you π I have been thinking about iOS. I may cover it after I finish up Android

20. SCHOW says:

This is amazing. You donot teach just one piece of code like everyone else. But you are getting us into the real stuff. I can tell you are very passionate about your work. Do you tutor people personally.? It would be great if you could?

• Derek Banas says:

Thank you for the compliment π I used to spend a lot of time teaching junior programmers. I basically feel like this medium allows me to reach many more people which is great.

21. MS says:

Derek, excellent tutorials. Any chance we can get a link to slideshare for the slides you are using in the videos?

• Derek Banas says:

Thank you π Sorry, but I deleted the slides. Sorry about that.

22. Youcef says:

Great tutorials. Keep unlocking knowledge. Thank You!

23. sam says:

Hi Derek this is amazing tutorial for my data structure class.you made my life easy. You are the man.