Getting started with Java algorithms

Getting started with Java algorithms

 

Insertion sort

Insertion Sort (Insertion Sort) is a simple and intuitive sorting algorithm. It works by constructing an ordered sequence. For unsorted data, scan from back to front in the sorted sequence, find the corresponding position and insert it. In the implementation of insertion sort, in the process of scanning from back to front, the sorted elements need to be moved backwards step by step to provide insertion space for the latest elements.

Basic idea:

Consider the n elements to be sorted as an ordered list and a non-ordered list. At the beginning, the ordered list has only 1 element, and the unordered list has n-1 elements;

Every time the first element is taken from the unordered list, it is inserted into the ordered list to make it a new ordered list, and the entire sorting process is completed by repeating n-1 times.

code show as below:

public class InsertSort {

    public static void getInsertSort(int[] a) {

        if(a == null || a.length == 0) {//Determine whether the array is empty

            System.out.println("The array is empty!");

            return;

        }

        int n = a.length;//The length of the array is assigned to n to prevent the length method from being called every time the for loop is judged to affect performance

        int temp;//It is placed outside the for loop to prevent repeated creation of variables

        int j;

        for(int i = 1; i <n;i++){//number of sorting

            temp = a[i];//Assign to temp is to prevent the element before index i from moving backward and covering the element of index i

            j = i-1;

            for(; j>=0&&a[j]>temp; --j) {//Move back the element larger than the element at position i

                a[j+1] = a[j];

            }

            a[j+1]= temp;//Find where i should be and place the value here

        }

    }

    public static void main(String[] args) {

        int[] a = {3, 5, 1, 2, 6, 4, 7, 11, 23, 44, 3, 34};

        getInsertSort(a);

        System.out.print("Direct insertion sort:");

        for(int i = 0; i < a.length; i++) {

            System.out.print(a[i] + " ");

        }

    }

}

 

Run it and output the result:

Direct insertion sort: 1 2 3 3 4 5 6 7 11 23 34 44 23

 

The strongest summary of ten classic sorting algorithms (including JAVA code implementation)

https://www.cnblogs.com/guoyaohua/p/8600214.html

 

 

Realization of Java singly linked list

What is a singly linked list

A singly linked list is one of the basic structures of a linked list. One of the simplest node structure is shown in the figure, which is the basic node structure that constitutes a singly linked list. In the node, the data field is used to store data elements, and the pointer field is used to point to the next node with the same structure.

 

[Three concepts in singly linked lists need to be clearly distinguished: head pointer, head node and head node.

Head node: Sometimes, an additional node is added before the first node of the linked list. The data field of the node generally does not store data (in some cases, the length of the linked list can also be stored). This node is called For the head node.

If the pointer field of the head node is NULL, it indicates that the linked list is an empty list. The head node is not necessary for the linked list. When dealing with some problems, adding a head node to the linked list will make the problem simple.

Head node: The node where the first element in the linked list is located. It is the first node behind the head node.

Head pointer: always point to the position of the first node in the linked list (if the linked list has a head node, the head pointer points to the head node; otherwise, the head pointer points to the head node).

The difference between the head node and the head pointer: the head pointer is a pointer, the head pointer points to the head node or the head node of the linked list; the head node is an actual node, which contains the data field and the pointer field. The direct manifestation of the two in the program is: the head pointer is only declared but no storage space is allocated, and the head node is declared and allocates the actual physical memory of a node.

There can be no head node in a singly linked list, but no head pointer! The introduction of the head node can make the deletion and insertion of the first element of the linked list the same as other elements, without additional explanation, making the code more concise.

 

The basic operations of a singly linked list include: add, delete, set, find, insert, etc.

 

Add element to singly linked list

  1. Declare a new node node as the new tail node, next=null;
  2. Get the last node of the original linked list, and point its next to the new node node in step 1
  3. Variable to record the length of the linked list +1

 

Delete element from singly linked list

  1. Get the previous node node of the node that needs to be deleted
  2. Point node's next to node's next
  3. Because the next node of node does not have a pointer to it, it will be automatically cleaned up by the system
  4. Variable to record the length of the linked list -1

 

Insert element in singly linked list

  1. Get the node at the position that needs to be inserted;
  2. Declare a new node node to point to the node obtained in step 1;
  3. Get the previous node that needs to be inserted into the position node;
  4. Point the next node of the node obtained in step 3 to the new node node;
  5. The variable that records the length of the linked list +1.

 

Simple operation realization of Java singly linked list

  1. Define the node class code as follows

package listTestPack;
//定义结点类
public class Node {
    private int data;
    public Node next;
    public Node(int data) {
        this.data = data;
    }
     
    public int getData() {
        return data;
    }
 
    public void setData(int data) {
        this.data = data;
    }
 
    public void display() {
        System.out.println("data="+data);
         
    }
     
}

 

2) Define the linked list operation class code as follows

package listTestPack;
//Define the linked list operation class
public class LinkList {     //Construct the head node     private Node first;     //Record the node position     private int pos=0;     public LinkList() {         this.first=null;     }     /**      * Insert a head node      */     public void input(int data) {         Node node=new Node(data);         node.next=first;         first=node;     }     /*      * Delete the head node and return to the head node      */     public Node delete() {         Node tmpeNode=first;         first = tmpeNode.next;         return first;     }     /*




     




















     * Arbitrary position addition point
     * /
public void addList (int i, int data) {     Node node = new Node (data);     Node useNode = first;     Node preNode = first;     while (i! = pos) {         preNode = useNode ;         useNode = useNode.next;         pos ++;     }     node.next = useNode;     preNode.next = node;     pos = 0; } / *  * Arbitrary position removal point  * / public Node delete (int i) {     Node preNode = first ;     Node UseNode = first;     an if (first == null) {         return first;     }     the while (! i = pos) {         PreNode = UseNode;








     















        useNode=useNode.next;
        pos++;
    }
    preNode.next=useNode.next;
    pos=0;
    return useNode;
}
/*
 * 头插法建立链表
 */
public void Initlist(int a[]) {
    for (int i = 0; i < a.length; i++) {
        Node node=new Node(a[i]);
        node.next=first;
        first=node;
    }
}
/*
 * 尾插法建链表
 */
public void InitList2(int a[]) {
    Node qNode=first;
    for (int i = 0; i < a.length; i++) {
        Node node=new Node(a[i]);
        qNode.next=node;
        qNode=node;
    }
 
}
/*
 * The query node information is the location of data
 */
public int findList(int data) {     Node useNode=first;     if(first==null) {         System.out.println("The linked list is empty!");         return 0;     }     while(useNode.getData()!=data) {         useNode=useNode.next;         pos++;     }     int i=pos;     pos=0;     System.out.println("The element is at the "+i+" position ");     return i; } /*  * Display node information in the linked list  */ public void displayall() {     Node useNode=first;     while(useNode!=null) {         useNode.display();         useNode=useNode.next;






















    }
    System.out.println();
    }
}

 

3) The test code is as follows:

package listTestPack;
//Test class
public class listTest {     public static void main(String[] args) {         // TODO Auto-generated method stub         LinkList laLinkList=new LinkList();         //Check the insertion header node         laLinkList.input(10 );         laLinkList.input(20);         laLinkList.input(30);         System.out.println("Display the inserted three head node elements");         laLinkList.displayall();         //Check to insert a node at any position         laLinkList. addList(1, 1);         laLinkList.addList(2, 2);         laLinkList.addList(3, 3);         System.out.println("Display the value of the inserted element at any position");         //Display node information         laLinkList. displayall();
















        //Delete the node with a value of 2
        System.out.println("Display delete function");
        Node deleNode=laLinkList.delete(2);
        System.out.println("=========== ====");
        //Display the information of deleting the node
        deleNode.display();
        System.out.println("==============");
        //Display all information
        laLinkList .displayall();
        System.out.println("---------------------");
        System.out.println("The following is the query");
        / /Query the position where the element is 3
        laLinkList.findList(3);
        System.out.println("---------------------");
        int a[]= {1,2,3,4,5};
        LinkList laLinkList2=new LinkList();
        //Head inserting method to build a linked list
        System.out.println("The following is the first insertion method to build a linked list");
        laLinkList2.Initlist(a);
        laLinkList2.displayall();
 
        System.out.println("The following is the tail insertion method");
        LinkList laLinkList3=new LinkList();
        //First insert a head node
        laLinkList3.input(0) ;
        laLinkList3.InitList2(a);
        laLinkList3.displayall();
        //Node n1=new Node(20);
        //n1.display();
     }
}

4) Use bluej to run the test

operation result:

 

Finally, give the code to realize isosceles triangle, right triangle, rhombus

 

☆Isosceles Triangle

public class IsoscelesTriangle {

    public static void main(String[] args){

        for(int i=1;i<=6;i++){

            for(int j =6;j>i;j--){

                System.out.print(" ");

            }

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

                System.out.print("*");

            }

            System.out.println();

        }

    }

}

 

☆Right Triangle

public class RightTriangle{

    public static void main(String[] args){

        for(int i=1; i<=6; i++){

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

             System.out.print("*");

             }

         System.out.println();

         }

    }

}

 

☆Print a rhombus Rhombus

public class Rhombus{

    public static void main(String[] args){

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

            for(int j=5;j>i;j--){

                System.out.print(" ");

            }

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

                System.out.print("*");

            }

            System.out.println();

        }

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

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

                System.out.print(" ");

            }

            for(int j=10;j>i*2+1;j--){

                System.out.print("*");

            }

            System.out.println();

        }

    }

}

 

 

appendix,

Java Basics-Realization of Single Link

https://blog.csdn.net/weixin_36605200/article/details/88804537

 

Guess you like

Origin blog.csdn.net/cnds123/article/details/112030717