"Algorithm" (1)--Dynamic connection and algorithm analysis __ algorithm

Source: Internet
Author: User
Tags arrays pow
Chapter of <Algorithms> (a)--dynamic connectivity and algorithm analysis
Basic Statement

This poster of algorithms are based on the book and the lecture of algorithms on Coursera which are taught by Robert Sedgewi CK and Kevin Wayne, writers of the book mentioned above.

Chapter of "algorithm" is the fundamental of Java programming language and a brief introduction to Algorithms and DA TA structure, including their concepts. Some interesting problems and the basic implementations of them. Introduction Why We study algorithms Their impact is broad and far-reaching. Old roots, new opportunities. To solve problems the could not otherwise is addressed. For intellectual stimulation. To become a proficient programmer. They may unlock the secrets and the universe. For fun and profit.

After summarizing some reason why we study algorithms, we could draw a conclusion that algorithms are widely used and we can Get more fun from it. Steps to developing a usable algorithm Model the problem find a algorithm to solve it Fast enough? Fits in memory? If not, figure out why find a way to address the problem iterate until satisfied

Developing a usable algorithm is the same as mathematical modeling which using iteration until the performance is Satisfie D. scientific Method:

Develop hypotheses about performance, create mathematical models. And run experiments to test them, repeating the process as necessary. algorithm

The term algorithm is used in computer science to describe a finite, deterministic, and effective problem-solving method s Uitable for implementation as a computer. Dynamic connectivity-union Find Form of Union find problem

Given a set of N objects.
-Union Command:connect Two objects
-find/connected Query:is There a path connecting the two objects? Quickfind

implementation of Quick-find Quickfind.java

/**
 * Created by williamyi
 * 3/11/2017
 * The direct implementation of Union-find
 connected * The two s have the same index
 * *

package quickfind;

public class Quickfind {
    private int[] ID;

    Set ID of each object to itself public
    void Quickfinduf (int N) {
        id = new Int[n];    
        for (int i = 0; i < N; i++) id[i] = i;
    }

    Check whether P and Q are connected public
    boolean connected (int p, int q) {return
        id[p] = = Id[q];
    }

    //change all entries and Id[p] to id[q the public
    Void Union (int p, int q) {
        int pid = id[p];
        int qid = id[q];
        for (int i = 0; i < id.length i++) {
            if (id[i] = = pid) id[i] = qid;
        }
    }
}
Quickfindtest.java
Package quickfind;

public class Quickfindtest {public
    static void Main (String [] args) {
        quickfind QF = new Quickfind ();
        Qf. Quickfinduf (6);
        Qf.union (0, 3);
        Qf.union (1, 4);
        Qf.union (4, 5);
        Qf.union (2, 5);
        System.out.println (qf.connected (1, 3));
        System.out.println (qf.connected (1, 2));
    }
quickunion

implementation of Quickunion Quickunion.java

/**
 * Created by williamyi
 * 3/11/2017
 * The Quick Union implementation of Union-find
 * * Package
Quic Kunion;

public class Quickunion {
    private int[] ID;

    public void Quickunionuf (int N) {
        id = new Int[n];
        for (int i = 0; i < N; i++) id[i] = i;
    }

    public int root (int i) {while
        (I!= id[i]) i = id[i];
        return i;
    }

    public boolean connected (int p, int q) {return
        root (p) = = root (q);
    }

    public void Union (int p, int q) {
        int i = root (p);
        Int j = root (q);
        Id[i] = j;
    }
}
Quickuniontest.java
Package quickunion;

public class Quickuniontest {public
    static void Main (string[] args) {
        quickunion qu = new quickunion ();

        Qu. Quickunionuf (6);
        Qu.union (0, 3);
        Qu.union (1, 4);
        Qu.union (4, 5);
        Qu.union (2, 5);
        System.out.println (qu.connected (1, 3));
        System.out.println (qu.connected (1, 2));
    }
weighted Quick Union

The main idea of weighted quick Union are to create a balance treee.

implementation of Weightedquickunion Weightedquickunion.java

Package weightedquickunion;

public class Weightedquickunion {
    private int[] ID;
    Private int[] sz;

    public void Weightedqu (int N) {
        id = new Int[n];
        SZ = new Int[n];
        for (int i = 0; i < N; i++) {
            id[i] = i;
            Sz[i] = 1;
        }}

    public int root (int i) {while
        (I!= id[i]) i = id[i];
        return i;
    }

    public void Union (int p, int q) {
        int i = root (p);
        Int j = root (q);
        if (i = = j) return;
        if (Sz[i] < sz[j]) {id[i] = J; Sz[j] + = Sz[i];
        else    {Id[j] = i; sz[i] + = Sz[j];
    }

    public boolean connected (int p, int q) {return
        root (p) = = root (q);
    }
Weightedqutest.java
Package weightedquickunion;

public class Weightedqutest {public
    static void Main (string[] args) {
        weightedquickunion wqu = new Weightedquicku Nion ();

        Wqu. Weightedqu (6);
        Wqu.union (0, 3);
        Wqu.union (1, 4);
        Wqu.union (4, 5);
        Wqu.union (2, 5);
        System.out.println (wqu.connected (1, 3));
        System.out.println (wqu.connected (1, 2));      Wqu. Weightedqu (6);      wqu.union (0, 1);      System.out.println (wqu.connected (1, 0));
    }
Analysis of algorithm scientific method applied to analysis of algorithms Scientific method ObserveSome feature of the natural world hypothesizeA model that's consistent with the observations predictEvents using the hypothesis VerifyThe predictions by making further observations ValidateBy repeating until the hypothesis and observations agree PrinciplesExperiments must be reporducible hypotheses must to be falsifiable Three-sum Description

Given N distinct integers, how many triples sum to exactly zero? Bruteforcemethod Bruteforcemethod.java

Package threesum;

public class Bruteforcemethod {public
    int numofthreesum (int[] a) {
        int count = 0;
        for (int i = 0; i < a.length. i++) for
            (int j = i+1 J < a.length; J +) for
                (int k = j+1; k < a.length; k++)
                    if (A[i] + a[j] + a[k] = = 0) {
                        System.out.println (A[i] + "" + A[j] + "" + "" + a[k]);
                        count++;
                    }   
        return count;
    }
}
Threesumtest.java
Package threesum;

public class Threesumtest {public
    static void Main (string[] args) {
        Bruteforcemethod BFM = new Bruteforcemethod ();

        int a[] = {0, -10, -40,};
        System.out.println (BFM. Numofthreesum (a));
    }
Time Calculator and Random Size Three Sum Stopwatch.java
Package threesum;

public class Stopwatch {
    private final long start;

    Public stopwatch () {
        start = System.currenttimemillis ();
    }

    Public double ElapsedTime () {
        Long now = System.currenttimemillis ();
        Return (Now-start)/1000.0;
    }
}
Bruteforcemethod.java
Package threesum;

public class Bruteforcemethod {public
    int numofthreesum (int[] a) {
        int count = 0;
        for (int i = 0; i < a.length. i++) for
            (int j = i+1 J < a.length; J +) for
                (int k = j+1; k < a.length; K + +)
                    if (A[i] + a[j] + a[k] = = 0) {
                        System.out.println (A[i] + "" + A[j] + "" + "" + a[k]);
                        count++;
                    }   
        return count;
    }
}
Threesumtest.java
Package threesum;

Import java.util.*;

public class Threesumtest {public
    static void Main (string[] args) {
        Scanner sc = new Scanner (system.in);

        System.out.print ("Please input the size:");
        int N = Sc.nextint ();

        int a[] = new Int[n];
        Bruteforcemethod BFM = new Bruteforcemethod ();

        Stopwatch timer = new stopwatch ();
        int a[] = {0, -10, -40,};
        for (int i = 0; i < N; i++) {
            //generate random # ranging from-10000 to 10000
            a[i] = (int) (Math.random () * 10000 * MATH.POW ( -1, (int) (Ten * Math.random ()));
        }
        System.out.println (BFM. Numofthreesum (a));
        Double time = Timer.elapsedtime ();
        System.out.println ("Running time are" + Time + "seconds");
    }
Binary Search Binarysearch.java
Package binarysearch;

public class BinarySearch {public
    int rank (int key, int[] a) {
        int lo = 0;
        int hi = a.length-1;
        Lo represent low, hi represent
        (lo <= hi) {
            int mid = lo + (Hi-lo)/2;
            Use this form instead of (Hi + lo)/2 because it can prevent overflow
            if (Key < A[mid) Hi = mid-1;
            else if (key > A[mid]) lo = mid + 1;
            else return mid;
        }
        Return-1
    }
}
Binarysearchtest.java
Package binarysearch;

Import Java.util.Arrays;
Import Java.util.Scanner;

public class Binarysearchtest {public
    static void Main (string[] args) {
        Scanner sc = new Scanner (system.in);
        BinarySearch bs = new BinarySearch ();

        int a[] = {11,23,54,68,15,18,19,56,35};
        Arrays.sort (a);

        System.out.println ("The sorted array is:");
        for (int i = 0; i < a.length i++) {
            System.out.print (A[i] + "  ");
        System.out.println ();

        System.out.print ("Please input the searching number:");
        int key = Sc.nextint ();
        System.out.print ("The index of the It is:" + bs.rank (key, a));
    }
An N2logn algorithm for Three-sum


Sortingbase3sum.java

Package sortingbased3sum;

Import Java.util.Arrays;

public class Sortingbased3sum {public
    int sortingbsedthreesum (int[] a) {
        int count = 0;
        Arrays.sort (a);
        for (int i = 0; i < a.length. i++) {for
            (int j = 1 + 1; j < A.length; J +) {
                If Arrays.binarysearch (A,-(a[i) +A[J]) >= 0) { 
                        System.out.println (A[i] + "" + A[j] + "" + (-a[i]-a[j));
                        count++
        }
        }} return count;
    }
}
Sortingbased3sumtest.java
Package sortingbased3sum;

Import Java.util.Scanner;

public class Sortingbased3sumtest {public
    static void Main (String [] args) {
Scanner sc = new Scanner (system.in);

        System.out.print ("Please input the size:");
        int N = Sc.nextint ();

        int a[] = new Int[n];
        Sortingbased3sum sortingbased3sum = new Sortingbased3sum ();

        int a[] = {0, -10, -40,};
        for (int i = 0; i < N; i++) {
            //generate random # ranging from-10000 to 10000
            a[i] = (int) (Math.random () * 10000 * MATH.POW ( -1, (int) (Ten * Math.random ()));
        }
        System.out.println (sortingbased3sum. Sortingbsedthreesum (a));
    }

End

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.