Tuesday, June 10, 2014

Source Code Rekursif Sederhana ( Faktorial, Trianguler Dll )

package TugasFadli;
public class rekursif {         
    double pr(double x, int n) {
        if (n == 0) {         
            return 1.0;   
        } else if (n > 0) {               
            return (x * pr(x, n - 1)); 
        } else {      
            return (1 / pr(x, -n)); 
        }                           
    }
}
class triangle {
    public static int t (int n) {    
        if (n == 1) {            
            return 1;                
        } else {                   
            return (n + t (n - 1));   
        }
    }
}
class other {
    public static int f(int x) {
        if (x == 0) {              
            return 0;               
        }                           
        return 2 * f(x - 1) + x * x;
    }
}
class cetak {
    public static void main(String[] args) {
        int x = 2, n = 3;
        rekursif hr = new rekursif();
        System.out.println("<+> HASIL <+>\n"
        + "Pngankat rekursif dari " + "" + x + "^" + n + " = " + hr.pr(x, n));
        triangle ht = new triangle();
        System.out.println("Bilangan triangle dari " + n + " = " + ht.t(n));
        other hf = new other();
        System.out.println( "Bilangan "+ x + " = " + hf.f(x));
       
    }
}

Contoh Source Code Buble Sort

package sorting;

public class buble {

    private long[] arr;
    private int jmlData;

    public buble(int max) {
        arr = new long[max];
        jmlData = 0;
    }
    public void tambah(long nilai) {
        arr[jmlData] = nilai;
        jmlData++;
    }
    public void bacaArr() {
        for (int i = 0; i < jmlData; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println(" ");
    }
    public void tukar(int a, int b) {
        long tamp = arr[a];
        arr[a] = arr[b];
        arr[b] = tamp;
    }
    public void bublesort() {
        for (int i = jmlData - 1; i > 0; i--) {
            for (int j = 0; j < i; j++) {
                if (arr[j] > arr[j + 1]) {
                    tukar(j, j + 1);
                    System.out.print("langkah ke - " + (-(i - jmlData)));
                    bacaArr();
                }
            }
        }
    }
}
class test {
    public static void main(String[] args) {
        int ukuran = 100;
        buble deret = new buble(ukuran);
        deret.tambah(2);
        deret.tambah(1);
        deret.tambah(4);
        deret.tambah(8);
        deret.tambah(0);
        deret.tambah(3);
        deret.tambah(5);

        System.out.println("data awal");
        deret.bacaArr();
        deret.bublesort();

        System.out.println("hasil pengurutan ");
        deret.bacaArr();
    }
}