Trending March 2024 # Java Program To Implement The Graph Data Structure # Suggested April 2024 # Top 7 Popular

You are reading the article Java Program To Implement The Graph Data Structure updated in March 2024 on the website Moimoishop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested April 2024 Java Program To Implement The Graph Data Structure

In this article, we will understand how to implement the graph data structure. we implement the graph data structure we implement graphs in Java using HashMap collection. HashMap elements are in the form of key-value pairs. We can represent the graph adjacency list in a HashMap.

Below is a demonstration of the same −

Suppose our input is −

Number of Vertices: 5 Number of edges: 5

The desired output would be −

The connections between the nodes of the Graph are: 1 - 2 1 - 3 1 - 4 2 - 4 2 - 5 3 - 4 3 - 5 4 - 5 Algorithm Step 1 - START Step 2 - Declare an object of a Graph class namely graph_object, two integers in class ‘Edge’ namely source and destination, and two integers in ‘main’ function namely vertices_count, edges_count. Step 3 - Define the values. Step 4 - Initialize values for the vertices and count. Step 5 - Create a new instance of the previously defined class. Step 6 - Initialize the instance with relevant values. Step 7 - Iterate over the instance using a ‘for’ loop, and display the output on the console. Step 8 - Display the result Step 9 - Stop Example 1

Here, we bind all the operations together under the ‘main’ function.

public class Graph {    class Edge {       int source, destination;    }    int vertices, edges;    Edge[] edge;    Graph(int vertices, int edges) {       this.vertices = vertices;       this.edges = edges;       edge = new Edge[edges];       for(int i = 0; i < edges; i++) {          edge[i] = new Edge();       }    }    public static void main(String[] args) {       int vertices_count = 5;       int edges_count = 8;       Graph graph_object = new Graph(vertices_count, edges_count);       System.out.println("A graph object is defined.");       graph_object.edge[0].source = 1;       graph_object.edge[0].destination = 2;       graph_object.edge[1].source = 1;       graph_object.edge[1].destination = 3;       graph_object.edge[2].source = 1;       graph_object.edge[2].destination = 4;       graph_object.edge[3].source = 2;       graph_object.edge[3].destination = 4;       graph_object.edge[4].source = 2;       graph_object.edge[4].destination = 5;       graph_object.edge[5].source = 3;       graph_object.edge[5].destination = 4;       graph_object.edge[6].source = 3;       graph_object.edge[6].destination = 5;       graph_object.edge[7].source = 4;       graph_object.edge[7].destination = 5;       System.out.println("The connections between the edges of the Graph are: ");       for(int i = 0; i < edges_count; i++) {          System.out.println(graph_object.edge[i].source + " - " + graph_object.edge[i].destination);       }    } } Output A graph object is defined. The connections between the edges of the Graph are: 1 - 2 1 - 3 1 - 4 2 - 4 2 - 5 3 - 4 3 - 5 4 - 5 Example 2

Here, we encapsulate the operations into functions exhibiting object-oriented programming.

public class Graph {    class Edge {       int source, destination;    }    int vertices, edges;    Edge[] edge;    Graph(int vertices, int edges) {       this.vertices = vertices;       this.edges = edges;       edge = new Edge[edges];       for(int i = 0; i < edges; i++) {          edge[i] = new Edge();       }    }    static void print(Graph graph_object,int edges_count){       System.out.println("The connections between the edges of the Graph are: ");       for(int i = 0; i < edges_count; i++) {          System.out.println(graph_object.edge[i].source + " - " + graph_object.edge[i].destination);       }    }    static void connect_edges(Graph graph_object){       graph_object.edge[0].source = 1;       graph_object.edge[0].destination = 2;       graph_object.edge[1].source = 1;       graph_object.edge[1].destination = 3;       graph_object.edge[2].source = 1;       graph_object.edge[2].destination = 4;       graph_object.edge[3].source = 2;       graph_object.edge[3].destination = 4;       graph_object.edge[4].source = 2;       graph_object.edge[4].destination = 5;       graph_object.edge[5].source = 3;       graph_object.edge[5].destination = 4;       graph_object.edge[6].source = 3;       graph_object.edge[6].destination = 5;       graph_object.edge[7].source = 4;       graph_object.edge[7].destination = 5;    }    public static void main(String[] args) {       int vertices_count = 5;       int edges_count = 8;       Graph graph_object = new Graph(vertices_count, edges_count);       System.out.println("A graph object is defined.");       connect_edges(graph_object);       print(graph_object, edges_count);    } } Output A graph object is defined. The connections between the edges of the Graph are: 1 - 2 1 - 3 1 - 4 2 - 4 2 - 5 3 - 4 3 - 5 4 - 5

You're reading Java Program To Implement The Graph Data Structure

C++ Program To Implement The Solovay

Solovay-Strassen Primality Test is used to test a number whether it is a composite or possibly prime number.

Algorithms Begin    Declare a function modulo to the long datatype to perform binary calculation.       Declare m_base, m_exp, m_mod of long datatype and pass them as a parameter.       Declare two variables a, b of long datatype.          Initialize a = 1, b = m_base.          if (m_exp % 2 == 1) then             a = (a * b) % m_mod.          b = (b * b) % m_mod.          m_exp = m_exp / 2.       Return a % m_mod. End Begin    Declare a function Jecobian of the int datatype to calculate Jacobian symbol of a given number.    Declare CJ_a, CJ_n of the long datatype and pass them as a parameter.    if (!CJ_a) then       return 0.    Declare answer of the integer datatype.       Initialize answer = 1.    if (CJ_a < 0) then       CJ_a = -CJ_a.       if (CJ_n % 4 == 3) then          answer = -answer.    if (CJ_a == 1) then       return answer.    while (CJ_a) do       if (CJ_a < 0) then          CJ_a = -CJ_a.          if (CJ_n % 4 == 3) then          answer = -answer.    while (CJ_a % 2 == 0) do       CJ_a = CJ_a / 2;          answer = -answer.    swap(CJ_a, CJ_n)    if (CJ_a % 4 == 3 && CJ_n % 4 == 3) then       answer = -answer.          CJ_a = CJ_a % CJ_n;       CJ_a = CJ_a - CJ_n.    if (CJ_n == 1) then       return answer. End Begin    Declare a function Solovoystrassen to the Boolean datatype to perform the Solovay-Strassen Primality Test.       Declare SS_p to the long datatype and pass as a parameter.       Declare itr to the integer datatype and pass them as a parameter.       if (SS_p < 2) then          return false.       if (SS_p != 2 && SS_p % 2 == 0) then          return false.       for (int i = 0; i < itr; i++)          long a = rand() % (SS_p - 1) + 1;          long jacob = (SS_p + Jacobian(a, SS_p)) % SS_p;          long mod = modulo(a, (SS_p - 1) / 2, SS_p);          return false       return true. End Begin    Declare iter of the integer datatype.       Initialize iter = 50.    Declare num1, num2 of the long datatype.    Print “Enter the first number:”    Input the value of num1.    if (Solovoystrassen(num1, iter)) then       print the value of num1 and ”is a prime number”.    Else       print the value of num1 and ”is a composite number”.    Print “Enter another number:”       Input the value of num2.    if (Solovoystrassen(num2, iter)) then       print the value of num2 and ”is a prime number”.    Else       print the value of num2 and ”is a composite number”. using namespace std; long modulo(long m_base, long m_exp, long m_mod) function to perform binary calculation {    long a = 1;    long b = m_base;       if (m_exp % 2 == 1)          a = (a * b) % m_mod;       b = (b * b) % m_mod;       m_exp = m_exp / 2;    }    return a % m_mod; } int Jacobian(long CJ_a, long CJ_n) {    if (!CJ_a)       return 0;// (0/n) = 0    int answer = 1;    if (CJ_a < 0) {       CJ_a = -CJ_a;       if (CJ_n % 4 == 3)          answer = -answer;    }    if (CJ_a == 1)       return answer;    while (CJ_a)  {       if (CJ_a < 0) {          CJ_a = -CJ_a;          if (CJ_n % 4 == 3)             answer = -answer;       }       while (CJ_a % 2 == 0) {          CJ_a = CJ_a / 2;             answer = -answer;       }       swap(CJ_a, CJ_n);       if (CJ_a % 4 == 3 && CJ_n % 4 == 3)          answer = -answer;       CJ_a = CJ_a % CJ_n;             CJ_a = CJ_a - CJ_n;    }    if (CJ_n == 1)       return answer;    return 0; } bool Solovoystrassen(long SS_p, int itr) {    if (SS_p < 2)       return false;    if (SS_p != 2 && SS_p % 2 == 0)       return false;    for (int i = 0; i < itr; i++) {             long a = rand() % (SS_p - 1) + 1;       long jacob = (SS_p + Jacobian(a, SS_p)) % SS_p;       long mod = modulo(a, (SS_p - 1) / 2, SS_p);          return false;    }    return true; } int main() {    int iter = 50;    long num1;    long num2;    cout<< "Enter the first number: ";    cout<<endl;    if (Solovoystrassen(num1, iter))       cout<<num1<<" is a prime numbern"<<endl;    else       cout<<num1<<" is a composite numbern"<<endl;       cout<<"Enter another number: ";    cout<<endl;    if (Solovoystrassen(num2, iter))       cout<<num2<<" is a prime numbern"<<endl;    else       cout<<num2<<" is a composite numbern"<<endl;    return 0; } Output Enter the first number: 24 24 is a composite number Enter another number: 23 23 is a prime number

Merge Sort In Data Structure

Introduction to Merge Sort in Data Structure

It is a recursive procedure based on the divide and conquers technique to solve a problem. This means it divides the main problem into smaller problems and later merges them to get the solution to the bigger one. In Merge Sort, we divide the list of elements into smaller lists until and unless the single element is left in the list and then these are merged in correct order to get the sorted list of elements. This is also a comparison-based sorting algorithm with O(nlogn) of complexity. Here we will discuss merge sort in a data structure along with its algorithm and applications.

Start Your Free Data Science Course

Algorithm for Merge Sort in Data Structure

Merge Sort works similar to quick Sort where one uses a divide and conquer algorithm to sort the array of elements. It uses a key process Merge(myarr, left,m, right) to combine the sub-arrays divided using m position element. This process works on one assumption that the two sub-arrays contain the elements in a sorted manner. Below is pseudo-code to implement Merge Sort for a given array myarr which has its last index as right.

Algorithm:

LArray[ i ] = A [ left + i -1] RArray[ j ]= A[ q + j ] if LArray[ i ] < R [ j ] A[ k ] = LArray[ i ] else A[ k ] = RArray[ j ] j = j + 1

Explanation: First, we have algorithm MERGE-SORT that takes an array as an argument and sees if the last index is greater than the left index to see if the array contains some elements to be sorted. Then a middle point m is calculated to divide the array into 2 sub-arrays, and the same algorithm is called for those sub-arrays. When recursive calls end and we end up having single elements in each sub-array, the MERGE algorithm is called.

This algorithm declares 2 arrays LArray and RArray to hold the elements in 2 sub-arrays. Then, elements in the 2 sub-arrays are compared simultaneously, and Array A is populated with elements in the sorted arrays. This algorithm is preferred over quick sort while working with the linked list as in quicksort, and there was a need to access the elements a lot which is of O(n) complexity in case of the linked list.

In the above picture, elements of the array are sorted using Merge sort. Also, we can see the sequence or the order in which the elements are processed.

Example to Implement Merge Sort in Data Structure

Here are some examples of implementing merge sort:

RArray = myarr[mid:] myarr[k] = LArray[i] myarr[k] = RArray[j] myarr[k] = LArray[i] myarr[k] = RArray[j] myarr = [45,12,86,3,24,36,9] printList(myarr)

Output:

Time Complexity

As it is a recursive algorithm, its time complexity can be expressed as a recurrence relation. Here are the 3 types of time complexity which are explained below:

T(n) = 2T(n/2) + Θ(n)

2. Average Case: This is the case when the elements are partially sorted. The complexity of merge sort, in this case, is Θ(nlogn).

3. Best Case: This is when all the elements are already sorted, but still recursive calls are made thus, complexity is Θ(nlogn).

And Complexity of Merge algorithm is O(n) in all cases. Thus Merge sort is a stable algorithm that uses O(n) of auxiliary space and Divides and Conquer paradigm to sort the list of elements.

Applications of Merge Sort

Here are some of the applications of merge sort which are explained below:

Sorting linked lists: Since random access of elements takes much time in case of the linked list, Merge Sort provides a quick solution to sort the linked list elements. This also stores the elements in self-made arrays and does not need random access in the linked list thus, and it provides a good solution to sort elements in O(nlogn).

Inversion Count Problem: This is a problem where the degree of sorting of elements is calculated in a list of array. N case array is sorted degree is 0, and in case of reverse sorted list degree becomes maximum.

Used internal Sorting: The type of sorting required to be done on data resides in secondary memory. This is required in case when the amount of data is too large to fit into the main memory. Since the memory location of data need not be contiguous in secondary memory thus merge sort is preferred.

Conclusion

Merge Sort is a divide and conquer algorithm that uses a merge process to merge the two sub-arrays into one by sorting its elements incorrect order. It works on one assumption that the elements in these sub-arrays are already sorted. This is a stable algorithm often used to sort the LinkedList or inversion count problems or external Sorting.

Recommended Articles

This is a guide to Merge Sort in Data Structure. Here we discuss the introduction, algorithm, and applications of Merge Sort in Data Structure and its code implementation. You can also go through our other suggested articles to learn more –

Java Program To Create A Calculator

To create a calculator with Java Swings, try the following code −

Example import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JTextField;

public class SwingDemo extends JFrame implements ActionListener {    JButton one, two, three, four, five, six, seven, eight, nine, num0, add, sub, div, mult, equalto, exit, point, reset;    JTextField textField;    String s = "", ope = "";    int flag = 0;    double total1;    double input1, input2;    void total(double input1, double inout2, String ope) {       String total;       if (ope.equalsIgnoreCase("+")) {          total1 = input1 + input2;          total = Double.toString(total1);          textField.setText(total);       } else if (ope.equalsIgnoreCase("-")) {          total1 = input1 - input2;          total = Double.toString(total1);          textField.setText(total);       } else if (ope.equalsIgnoreCase("*")) {          total1 = input1 * input2;          total = Double.toString(total1);          textField.setText(total);       } else if (ope.equalsIgnoreCase("/")) {          total1 = input1 / input2;          total = Double.toString(total1);          textField.setText(total);       }          }    public SwingDemo() {       Container container = getContentPane();       container.setLayout(new FlowLayout());       JLabel jl = new JLabel(" My Demo Calculator ");       textField = new JTextField(15);       one = new JButton(" 1 ");       two = new JButton(" 2 ");       three = new JButton(" 3 ");       four = new JButton(" 4 ");       five = new JButton(" 5 ");       six = new JButton(" 6 ");       seven = new JButton(" 7 ");       eight = new JButton(" 8 ");       nine = new JButton(" 9 ");       num0 = new JButton(" 0 ");       add = new JButton(" + ");       sub = new JButton(" - ");       div = new JButton(" / ");       mult = new JButton(" * ");       equalto = new JButton(" = ");       exit = new JButton(" Exit ");       point = new JButton(" . ");       reset = new JButton("C");       reset.setBackground(Color.YELLOW);             one.addActionListener(this);       two.addActionListener(this);       three.addActionListener(this);       four.addActionListener(this);       five.addActionListener(this);       six.addActionListener(this);       seven.addActionListener(this);       eight.addActionListener(this);       nine.addActionListener(this);       num0.addActionListener(this);       add.addActionListener(this);       sub.addActionListener(this);       mult.addActionListener(this);       div.addActionListener(this);       equalto.addActionListener(this);       exit.addActionListener(this);       point.addActionListener(this);       reset.addActionListener(this);       container.add(jl);       container.add(textField);       container.add(one);       container.add(two);       container.add(three);       container.add(add);       container.add(four);       container.add(five);       container.add(six);       container.add(sub);       container.add(seven);       container.add(eight);       container.add(nine);       container.add(div);       container.add(num0);       container.add(point);       container.add(mult);       container.add(equalto);       container.add(reset);       container.add(exit);    }    public static void main(String arg[]) {       SwingDemo d = new SwingDemo();       d.setSize(260, 300);       d.setVisible(true);    }    public void actionPerformed(ActionEvent e) {       Object o = e.getSource();       if (o == one) {          textField.setText(s.concat("1"));          s = textField.getText();       } else if (o == two) {          textField.setText(s.concat("2"));          s = textField.getText();       } else if (o == three) {          textField.setText(s.concat("3"));          s = textField.getText();       } else if (o == four) {          textField.setText(s.concat("4"));          s = textField.getText();       } else if (o == five) {          textField.setText(s.concat("5"));          s = textField.getText();       } else if (o == six) {          textField.setText(s.concat("6"));          s = textField.getText();       } else if (o == seven) {          textField.setText(s.concat("7"));          s = textField.getText();       } else if (o == eight) {          textField.setText(s.concat("8"));          s = textField.getText();       } else if (o == nine) {          textField.setText(s.concat("9"));          s = textField.getText();       } else if (o == num0) {          textField.setText(s.concat("0"));          s = textField.getText();       } else if (o == add) {          textField.setText("");          input1 = Double.parseDouble(s);          System.out.println(input1);          s = "";          ope = "+";       } else if (o == sub) {          textField.setText("");          input1 = Double.parseDouble(s);          s = "";          ope = "-";       } else if (o == mult) {          textField.setText("");          input1 = Double.parseDouble(s);          s = "";          ope = "*";       } else if (o == div) {          textField.setText("");          input1 = Double.parseDouble(s);          s = "";          ope = "/";       } else if (o == equalto) {          if (flag == 0) {             input2 = Double.parseDouble(s);             total(input1, input2, ope);             flag = 1;          } else if (flag == 1) {             input2 = Double.parseDouble(s);             total(input1, input2, ope);          }          System.out.println(input1);       } else if (o == exit) {          System.exit(0);       } else if (o == point) {          textField.setText(s.concat("."));          s = textField.getText();       }       if (o == reset) {          textField.setText("");          s = textField.getText();          total1 = 0;       }    }

Data Structure And Algorithms Insertion Sort

Data Structure and Algorithms Insertion Sort

This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be ‘insert’ed in this sorted sub-list, has to find its appropriate place and then it has to be inserted there. Hence the name, insertion sort.

The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array). This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n2), where n is the number of items.

How Insertion Sort Works?

We take an unsorted array for our example.

Insertion sort compares the first two elements.

It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.

Insertion sort moves ahead and compares 33 with 27.

And finds that 33 is not in the correct position.

It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see that the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the sorted sub-list remains sorted after swapping.

By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.

These values are not in a sorted order.

So we swap them.

However, swapping makes 27 and 10 unsorted.

Hence, we swap them too.

Again we find 14 and 10 in an unsorted order.

We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items.

This process goes on until all the unsorted values are covered in a sorted sub-list. Now we shall see some programming aspects of insertion sort.

Algorithm

Now we have a bigger picture of how this sorting technique works, so we can derive simple steps by which we can achieve insertion sort.

Step 1 − If it is the first element, it is already sorted. return 1; Step 2 − Pick next element Step 3 − Compare with all elements in the sorted sub-list Step 4 − Shift all the elements in the sorted sub-list that is greater than the value to be sorted Step 5 − Insert the value Step 6 − Repeat until list is sorted Pseudocode procedure insertionSort( A : array of items ) int holePosition int valueToInsert for i = 1 to length(A) inclusive do: /* select value to be inserted */ valueToInsert = A[i] holePosition = i /*locate hole position for the element to be inserted */ A[holePosition] = A[holePosition-1] holePosition = holePosition -1 end while /* insert the number at hole position */ A[holePosition] = valueToInsert end for end procedure

Advertisements

Java Program To Access All The Constant Defined In The Enum

After JDK version 5 java introduces the enumeration. It is a group of constants defined using the keyword ‘enum’. The final variables in java are somewhat similar to enumeration.

In this article, we will make a java program in which we define an enum class and try to access all the constant defined in the enum by using valueOf() and values() methods.

Enum

We use enum class when we need to define a fixed set of constants. For example, if we want to use the days of the week, planet names, names of all five vowels etc. Note that all the names of constants are declared in uppercase letters.

Although enum is a class type in java, we can’t instantiate it. Each constant defined in an enum is the instance of its enum type. It provides other functionalities of a class like we can create its instance variables, methods and constructors.

Syntax Enum enumeration_name { } Example enum Planet { EARTH, MARS, JUPYTER, NEPTUNE, SATURN, URANUS, VENUS; }

The above example illustrates how we can create an enum class. Name of the enum is Planet and the variables EARTH, MARS are its constants. By default, they are declared as public and static. These constants are self-typed because their type is defined by the enumeration in which they are defined. In this case, they are of Planet type.

Program to Access all Constant defined in the Enum

valueOf() and values() are the two predefined methods that will help us to get the values of constants defined in the list.

valueOf() − It returns the value of constant that is passed as argument.

values() − It returns an array that contains all the constants present in enum class.

Example 1

The following example demonstrates how we can get the constants by using valueOf() method &minuns;

enum Vibgyor { VIOLET, INDIGO, BLUE, GREEN, YELLOW, ORANGE, RED; } public class Main { public static void main(String[] args) { System.out.println("The color present in VIBGYOR: "); Vibgyor color = Vibgyor.ORANGE; System.out.println(color + " is present at index: " + color.ordinal()); Vibgyor colr = Vibgyor.valueOf("INDIGO"); System.out.println(colr); System.out.print(Vibgyor.valueOf("RED")); } } Output The color present in VIBGYOR: ORANGE is present at index: 5 INDIGO RED

In the above program, we have created an enum ‘Vibgyor’ with some constants. The two variables ‘color’ and ‘colr’ are the enumeration variable of type Vibgyor. Using these variables we have fetched the constants. Using valueOf() method we can get one item at a time. The ordinal() method is used here to access the index value of ORANGE. Indexing starts from 0. We can also access the constant without creating any variable.

Example 2

The following example demonstrates how we can get the constants by using values() method −

enum Vibgyor { VIOLET, INDIGO, BLUE, GREEN, YELLOW, ORANGE, RED; } public class Main { public static void main(String[] args) { System.out.println("The color present in VIBGYOR: "); for(Vibgyor color : Vibgyor.values()) { System.out.println(color); } } } Output The color present in VIBGYOR: VIOLET INDIGO BLUE GREEN YELLOW ORANGE RED

In the above program, we have accessed all the constants with a single for each loop. values() method can access multiple values at a time.

Conclusion

In this article, we have discussed enum and its methods. We have created java program to understand how we can access all the constants defined in the enum using values() and valueOf() methods.

Update the detailed information about Java Program To Implement The Graph Data Structure on the Moimoishop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!