DSA using Java – Sorting techniques

DSA using Java – Sorting techniques ”; Previous Next Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange data in a particular order. Most common orders are numerical or lexicographical order. Importance of sorting lies in the fact that data searching can be optimized to a very high level if data is stored in a sorted manner. Sorting is also used to represent data in more readable formats. Some of the examples of sorting in real life scenarios are following. Telephone Directory − Telephone directory keeps telephone no. of people sorted on their names. So that names can be searched. Dictionary − Dictionary keeps words in alphabetical order so that searching of any work becomes easy. Types of Sorting Following is the list of popular sorting algorithms and their comparison. Sr.No Technique & Description 1 Bubble Sort Bubble sort is simple to understand and implement algorithm but is very poor in performance. 2 Selection Sort Selection sort as name specifies use the technique to select the required item and prepare sorted array accordingly. 3 Insertion Sort Insertion sort is a variation of selection sort. 4 Shell Sort Shell sort is an efficient version of insertion sort. 5 Quick Sort Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays. 6 Sorting Objects Java objects can be sorted easily using java.util.Arrays.sort() Print Page Previous Next Advertisements ”;

DSA using Java – Useful Resources

DSA using Java – Useful Resources ”; Previous Next The following resources contain additional information on DSA using Java. Please use them to get more in-depth knowledge on this. Useful Links on DSA using Java DSA using Java @ Wikipedia − DSA using Java, its history and various other terms has been explained in simple language. Useful Books on DSA using Java To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

DSA using Java – Quick Guide

DSA using Java – Quick Guide ”; Previous Next DSA using Java – Overview What is a Data Structure? Data Structure is a way to organized data in such a way that it can be used efficiently. Following terms are foundation terms of a data structure. Interface − Each data strucure has an interface. Interface represents the set of operations that a datastructure supports.An interface only provides the list of supported operations, type of parameters they can accept and return type of these operations. Implementation − Implementation provides the internal representation of a data structure. Implementation also provides the defination of the alogrithms used in the opreations of the data structure. Characteristics of a Data Structure Correctness − Data Structure implementation should implement its interface correctly. Time Complexity − Running time or execution time of operations of data structure must be as small as possible. Space Complexity − Memory usage of a data structure operation should be as little as possible. Need for Data Structure As applications are getting complex and data rich, there are three common problems applications face now-a-days. Data Search − Consider an inventory of 1 million(106) items of a store. If application is to search an item. It has to search item in 1 million(106) items every time slowing down the search. As data grows, search will become slower. Processor speed − Processor speed although being very high, falls limited if data grows to billon records. Multiple requests − As thousands of users can search data simultaneously on a web server,even very fast server fails while searching the data. To solve above problems, data structures come to rescue. Data can be organized in a data structure in such a way that all items may not be required to be search and required data can be searched almost instantly. Execution Time Cases There are three cases which are usual used to compare various data structure”s execution time in relative manner. Worst Case − This is the scenario where a particular data structure operation takes maximum time it can take. If a operation”s worst case time is ƒ(n) then this operation will not take time more than ƒ(n) time where ƒ(n) represents function of n. Average Case − This is the scenario depicting the average execution time of an operation of a data structure. If a operation takes ƒ(n) time in execution then m operations will take mƒ(n) time. Best Case − This is the scenario depicting the least possible execution time of an operation of a data structure. If a operation takes ƒ(n) time in execution then actual operation may take time as random number which would be maximum as ƒ(n). DSA using Java – Environment Setup Local Environment Setup If you are still willing to setup your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the following steps to set up the environment. Java SE is freely available from the link Download Java. So you download a version based on your operating system. Follow the instructions to download java and run the .exe to install Java on your machine. Once you installed Java on your machine, you would need to set environment variables to point to correct installation directories: Setting up the path for windows 2000/XP Assuming you have installed Java in c:Program Filesjavajdk directory: Right-click on ”My Computer” and select ”Properties”. Click on the ”Environment variables” button under the ”Advanced” tab. Now alter the ”Path” variable so that it also contains the path to the Java executable. Example, if the path is currently set to ”C:WINDOWSSYSTEM32”, then change your path to read ”C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin”. Setting up the path for windows 95/98/ME Assuming you have installed Java in c:Program Filesjavajdk directory − Edit the ”C:autoexec.bat” file and add the following line at the end: ”SET PATH=%PATH%;C:Program Filesjavajdkbin” Setting up the path for Linux, UNIX, Solaris, FreeBSD: Environment variable PATH should be set to point to where the java binaries have been installed. Refer to your shell documentation if you have trouble doing this. Example, if you use bash as your shell, then you would add the following line to the end of your ”.bashrc: export PATH=/path/to/java:$PATH” Popular Java Editors To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following: Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Netbeans −is a Java IDE that is open source and free which can be downloaded from https://www.netbeans.org/index.html. Eclipse − is also a java IDE developed by the eclipse open source community and can be downloaded from https://www.eclipse.org/. What is Next ? Next chapter will teach you how to write and run your first java program and some of the important basic syntaxes in java needed for developing applications. DSA using Java – Algorithms Algorithm concept Algorithm is a step by step procedure, which defines a set of instructions to be executed in certain order to get the desired output. In term of data structures, following are the categories of algorithms. Search − Algorithms to search an item in a datastrucure. Sort − Algorithms to sort items in certain order Insert − Algorithm to insert item in a datastructure Update − Algorithm to update an existing item in a data structure Delete − Algorithm to delete an existing item from a data structure Algorithm analysis Algorithm analysis deals with the execution time or running time of various operations of a data structure. Running time of an operation can be defined as no. of computer instructions executed per operation. As exact running time of any operation varies from one computer to another computer, we usually analyze the running time of any operation as some function of n, where n is the no. of items processed in that operation in a

DSA using Java – Priority Queue

DSA using Java – Priority Queue ”; Previous Next Overview Priority Queue is more specilized data structure than Queue. Like ordinary queue, priority queue has same method but with a major difference. In Priority queue items are ordered by key value so that item with the lowest value of key is at front and item with the highest value of key is at rear or vice versa. So we”re assigned priority to item based on its key value. Lower the value, higher the priority. Following are the principal methods of a Priority Queue. Basic Operations insert / enqueue − add an item to the rear of the queue. remove / dequeue − remove an item from the front of the queue. Priority Queue Representation We”re going to implement Queue using array in this article. There is few more operations supported by queue which are following. Peek − get the element at front of the queue. isFull − check if queue is full. isEmpty − check if queue is empty. Insert / Enqueue Operation Whenever an element is inserted into queue, priority queue inserts the item according to its order. Here we”re assuming that data with high value has low priority. public void insert(int data){ int i =0; if(!isFull()){ // if queue is empty, insert the data if(itemCount == 0){ intArray[itemCount++] = data; }else{ // start from the right end of the queue for(i = itemCount – 1; i >= 0; i– ){ // if data is larger, shift existing item to right end if(data > intArray[i]){ intArray[i+1] = intArray[i]; }else{ break; } } // insert the data intArray[i+1] = data; itemCount++; } } } Remove / Dequeue Operation Whenever an element is to be removed from queue, queue get the element using item count. Once element is removed. Item count is reduced by one. public int remove(){ return intArray[–itemCount]; } Priority Queue Implementation PriorityQueue.java package com.tutorialspoint.datastructure; public class PriorityQueue { private final int MAX; private int[] intArray; private int itemCount; public PriorityQueue(int size){ MAX = size; intArray = new int[MAX]; itemCount = 0; } public void insert(int data){ int i =0; if(!isFull()){ // if queue is empty, insert the data if(itemCount == 0){ intArray[itemCount++] = data; }else{ // start from the right end of the queue for(i = itemCount – 1; i >= 0; i– ){ // if data is larger, shift existing item to right end if(data > intArray[i]){ intArray[i+1] = intArray[i]; }else{ break; } } // insert the data intArray[i+1] = data; itemCount++; } } } public int remove(){ return intArray[–itemCount]; } public int peek(){ return intArray[itemCount – 1]; } public boolean isEmpty(){ return itemCount == 0; } public boolean isFull(){ return itemCount == MAX; } public int size(){ return itemCount; } } Demo Program PriorityQueueDemo.java package com.tutorialspoint.datastructure; public class PriorityQueueDemo { public static void main(String[] args){ PriorityQueue queue = new PriorityQueue(6); //insert 5 items queue.insert(3); queue.insert(5); queue.insert(9); queue.insert(1); queue.insert(12); // —————— // index : 0 1 2 3 4 // —————— // queue : 12 9 5 3 1 queue.insert(15); // ——————— // index : 0 1 2 3 4 5 // ——————— // queue : 15 12 9 5 3 1 if(queue.isFull()){ System.out.println(“Queue is full!”); } //remove one item int num = queue.remove(); System.out.println(“Element removed: “+num); // ——————— // index : 0 1 2 3 4 // ——————— // queue : 15 12 9 5 3 //insert more items queue.insert(16); // ———————- // index : 0 1 2 3 4 5 // ———————- // queue : 16 15 12 9 5 3 //As queue is full, elements will not be inserted. queue.insert(17); queue.insert(18); // ———————- // index : 0 1 2 3 4 5 // ———————- // queue : 16 15 12 9 5 3 System.out.println(“Element at front: “+queue.peek()); System.out.println(“———————-“); System.out.println(“index : 5 4 3 2 1 0”); System.out.println(“———————-“); System.out.print(“Queue: “); while(!queue.isEmpty()){ int n = queue.remove(); System.out.print(n +” “); } } } If we compile and run the above program then it would produce following result − Queue is full! Element removed: 1 Element at front: 3 ———————- index : 5 4 3 2 1 0 ———————- Queue: 3 5 9 12 15 16 Print Page Previous Next Advertisements ”;

DSA using Java – Recursion

DSA using Java – Recursion ”; Previous Next Overview Recursion refers to a technique in a programming language where a function calls itself. The function which calls itself is called a recursive method. Characteristics A recursive function must posses the following two characteristics Base Case(s) Set of rules which leads to base case after reducing the cases. Recursive Factorial Factorial is one of the classical example of recursion. Factorial is a non-negative number satisfying following conditions. 0! = 1 1! = 1 n! = n * n-1! Factorial is represented by “!”. Here Rule 1 and Rule 2 are base cases and Rule 3 are factorial rules. As an example, 3! = 3 x 2 x 1 = 6 private int factorial(int n){ //base case if(n == 0){ return 1; }else{ return n * factorial(n-1); } } Recursive Fibonacci Series Fibonacci Series is another classical example of recursion. Fibonacci series a series of integers satisfying following conditions. F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2 Fibonacci is represented by “F”. Here Rule 1 and Rule 2 are base cases and Rule 3 are fibonnacci rules. As an example, F5 = 0 1 1 2 3 Demo Program RecursionDemo.java package com.tutorialspoint.algorithm; public class RecursionDemo { public static void main(String[] args){ RecursionDemo recursionDemo = new RecursionDemo(); int n = 5; System.out.println(“Factorial of ” + n + “: “ + recursionDemo.factorial(n)); System.out.print(“Fibbonacci of ” + n + “: “); for(int i=0;i<n;i++){ System.out.print(recursionDemo.fibbonacci(i) +” “); } } private int factorial(int n){ //base case if(n == 0){ return 1; }else{ return n * factorial(n-1); } } private int fibbonacci(int n){ if(n ==0){ return 0; } else if(n==1){ return 1; } else { return (fibbonacci(n-1) + fibbonacci(n-2)); } } } If we compile and run the above program then it would produce following result − Factorial of 5: 120 Fibbonacci of 5: 0 1 1 2 3 Print Page Previous Next Advertisements ”;

DSA using Java – Overview

DSA using Java – Overview ”; Previous Next What is a Data Structure? Data Structure is a way to organized data in such a way that it can be used efficiently. Following terms are foundation terms of a data structure. Interface − Each data strucure has an interface. Interface represents the set of operations that a datastructure supports.An interface only provides the list of supported operations, type of parameters they can accept and return type of these operations. Implementation − Implementation provides the internal representation of a data structure. Implementation also provides the defination of the alogrithms used in the opreations of the data structure. Characteristics of a Data Structure Correctness − Data Structure implementation should implement its interface correctly. Time Complexity − Running time or execution time of operations of data structure must be as small as possible. Space Complexity − Memory usage of a data structure operation should be as little as possible. Need for Data Structure As applications are getting complex and data rich, there are three common problems applications face now-a-days. Data Search − Consider an inventory of 1 million(106) items of a store. If application is to search an item. It has to search item in 1 million(106) items every time slowing down the search. As data grows, search will become slower. Processor speed − Processor speed although being very high, falls limited if data grows to billon records. Multiple requests − As thousands of users can search data simultaneously on a web server,even very fast server fails while searching the data. To solve above problems, data structures come to rescue. Data can be organized in a data structure in such a way that all items may not be required to be search and required data can be searched almost instantly. Execution Time Cases There are three cases which are usual used to compare various data structure”s execution time in relative manner. Worst Case − This is the scenario where a particular data structure operation takes maximum time it can take. If a operation”s worst case time is ƒ(n) then this operation will not take time more than ƒ(n) time where ƒ(n) represents function of n. Average Case − This is the scenario depicting the average execution time of an operation of a data structure. If a operation takes ƒ(n) time in execution then m operations will take mƒ(n) time. Best Case − This is the scenario depicting the least possible execution time of an operation of a data structure. If a operation takes ƒ(n) time in execution then actual operation may take time as random number which would be maximum as ƒ(n). Print Page Previous Next Advertisements ”;

DSA using Java – Circular Linked List

DSA using Java – Circular Linked List ”; Previous Next Circular Linked List Basics Circular Linked List is a variation of Linked list in which first element points to last element and last element points to first element. Both Singly Linked List and Doubly Linked List can be made into as circular linked list Singly Linked List as Circular Doubly Linked List as Circular As per above shown illustrations, following are the important points to be considered. Last Link”next points to first link of the list in both cases of singly as well as doubly linked list. First Link”s prev points to the last of the list in case of doubly linked list. Basic Operations Following are the important operations supported by a circular list. insert − insert an element in the start of the list. delete − insert an element from the start of the list. display − display the list. length Operation Following code demonstrate insertion operation at in a circular linked list based on single linked list. //insert link at the first location public void insertFirst(int key, int data){ //create a link Link link = new Link(key,data); if (isEmpty()) { first = link; first.next = first; } else{ //point it to old first node link.next = first; //point first to new first node first = link; } } Deletion Operation Following code demonstrate deletion operation at in a circular linked list based on single linked list. //delete link at the first location public Link deleteFirst(){ //save reference to first link Link tempLink = first; //if only one link if(first.next == null){ last = null; }else { first.next.prev = null; } first = first.next; //return the deleted link return tempLink; } Display List Operation Following code demonstrate display list operation in a circular linked list. public void display(){ //start from the beginning Link current = first; //navigate till the end of the list System.out.print(“[ “); if(first != null){ while(current.next != current){ //print data current.display(); //move to next item current = current.next; System.out.print(” “); } } System.out.print(” ]”); } Demo Link.java package com.tutorialspoint.list; public class CircularLinkedList { //this link always point to first Link private Link first; // create an empty linked list public CircularLinkedList(){ first = null; } public boolean isEmpty(){ return first == null; } public int length(){ int length = 0; //if list is empty if(first == null){ return 0; } Link current = first.next; while(current != first){ length++; current = current.next; } return length; } //insert link at the first location public void insertFirst(int key, int data){ //create a link Link link = new Link(key,data); if (isEmpty()) { first = link; first.next = first; } else{ //point it to old first node link.next = first; //point first to new first node first = link; } } //delete first item public Link deleteFirst(){ //save reference to first link Link tempLink = first; if(first.next == first){ first = null; return tempLink; } //mark next to first link as first first = first.next; //return the deleted link return tempLink; } public void display(){ //start from the beginning Link current = first; //navigate till the end of the list System.out.print(“[ “); if(first != null){ while(current.next != current){ //print data current.display(); //move to next item current = current.next; System.out.print(” “); } } System.out.print(” ]”); } } DoublyLinkedListDemo.java package com.tutorialspoint.list; public class CircularLinkedListDemo { public static void main(String args[]){ CircularLinkedList list = new CircularLinkedList(); list.insertFirst(1, 10); list.insertFirst(2, 20); list.insertFirst(3, 30); list.insertFirst(4, 1); list.insertFirst(5, 40); list.insertFirst(6, 56); System.out.print(“nOriginal List: “); list.display(); System.out.println(“”); while(!list.isEmpty()){ Link temp = list.deleteFirst(); System.out.print(“Deleted value:”); temp.display(); System.out.println(“”); } System.out.print(“List after deleting all items: “); list.display(); System.out.println(“”); } } If we compile and run the above program then it would produce following result − Original List: [ {6,56} {5,40} {4,1} {3,30} {2,20} ] Deleted value:{6,56} Deleted value:{5,40} Deleted value:{4,1} Deleted value:{3,30} Deleted value:{2,20} Deleted value:{1,10} List after deleting all items: [ ] Print Page Previous Next Advertisements ”;

DSA using Java – Data Structures

DSA using Java – Data Structures ”; Previous Next Data Structure is a way to organized data in such a way that it can be used efficiently. Following terms are basic terms of a data structure. Data Definition Data Definition defines a particular data with following characteristics. Atomic − Defition should define a single concept Traceable − Definition should be be able to be mapped to some data element. Accurate − Definition should be unambiguous. Clear and Concise − Definition should be understandable. Data Object Data Object represents an object having a data. Data Type Data type is way to classify various types of data such as integer, string etc. which determines the values that can be used with the corresponding type of data, the type of operations that can be performed on the corresponding type of data. Data type of two types − Built-in Data Type Derived Data Type Built-in Data Type Those data types for which a language has built-in support are known as Built-in Data types. For example, most of the languages provides following built-in data types. Integers Boolean (true, false) Floating (Decimal numbers) Character and Strings Derived Data Type Those data types which are implementation independent as they can be implemented in one or other way are known as derived data types. These data types are normally built by combination of primary or built-in data types and associated operations on them. For example − List Array Stack Queue Print Page Previous Next Advertisements ”;

DSA using Java – Environment Setup

DSA using Java – Environment Setup ”; Previous Next Local Environment Setup If you are still willing to setup your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the following steps to set up the environment. Java SE is freely available from the link Download Java. So you download a version based on your operating system. Follow the instructions to download java and run the .exe to install Java on your machine. Once you installed Java on your machine, you would need to set environment variables to point to correct installation directories: Setting up the path for windows 2000/XP Assuming you have installed Java in c:Program Filesjavajdk directory: Right-click on ”My Computer” and select ”Properties”. Click on the ”Environment variables” button under the ”Advanced” tab. Now alter the ”Path” variable so that it also contains the path to the Java executable. Example, if the path is currently set to ”C:WINDOWSSYSTEM32”, then change your path to read ”C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin”. Setting up the path for windows 95/98/ME Assuming you have installed Java in c:Program Filesjavajdk directory − Edit the ”C:autoexec.bat” file and add the following line at the end: ”SET PATH=%PATH%;C:Program Filesjavajdkbin” Setting up the path for Linux, UNIX, Solaris, FreeBSD: Environment variable PATH should be set to point to where the java binaries have been installed. Refer to your shell documentation if you have trouble doing this. Example, if you use bash as your shell, then you would add the following line to the end of your ”.bashrc: export PATH=/path/to/java:$PATH” Popular Java Editors To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following: Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Netbeans −is a Java IDE that is open source and free which can be downloaded from https://www.netbeans.org/index.html. Eclipse − is also a java IDE developed by the eclipse open source community and can be downloaded from https://www.eclipse.org/. What is Next ? Next chapter will teach you how to write and run your first java program and some of the important basic syntaxes in java needed for developing applications. Print Page Previous Next Advertisements ”;

DSA using Java – Home

DSA using Java Tutorial PDF Version Quick Guide Resources Job Search Discussion Data Structures are the programmetic way of storing data so that data can be used efficiently. Almost every enterprise applicaton uses various types of data structures in one or other way. This tutorial will give you great understanding on Data Structures concepts needed to understand the complexity of enterprise level applications and need of algorithms, data structures. Audience This tutorial is designed for Computer Science graduatates as well as Software Professionals who are willing to learn Data Structures and algorithm Programming in simple and easy steps. This tutorial will give you great understanding on Data Structuress concepts and after completing this tutorial you will be at intermediate level of expertise from where you can take yourself at higher level of expertise. Prerequisites Before proceeding with this tutorial you should have a basic understanding of Java programming language, text editor and execution of programs etc. Print Page Previous Next Advertisements ”;