搜尋此網誌

顯示具有 演算法 標籤的文章。 顯示所有文章
顯示具有 演算法 標籤的文章。 顯示所有文章

2013年1月7日 星期一

BST with Java implementation

The removal part is all from Algorithms and Data Structures with implementations in Java and C++ . I just add some comments.


public class BST {

    public static void main(String[] args) {
        Tree myBst = new Tree();
        Node one = new Node(1);
        Node six = new Node(6);
        Node three = new Node(3);
        Node five = new Node(5);
        Node two = new Node(2);

        myBst.insert(one);
        myBst.insert(six);
        myBst.insert(three);
        myBst.insert(five);
        myBst.insert(two);
        myBst.preOrderTraversal(myBst.root);
        System.out.println("-----------------");
        myBst.remove(3);
        myBst.preOrderTraversal(myBst.root);

    }

}

class Node {
    Node leftChild;
    Node rightChild;
    int value;

    Node(int i) {
        this.value = i;
    }

    public boolean remove(int value, Node parent) {
        if (value < this.value) {//not found, keep left search
            if (leftChild != null)
                return leftChild.remove(value, this);
            else
                return false;
        } else if (value > this.value) {//not found , keep right search.
            if (rightChild != null)
                return rightChild.remove(value, this);
            else
                return false;
        } else {//found
            if (leftChild != null && rightChild != null) {//two leafs case
                this.value = rightChild.minValue();
                rightChild.remove(this.value, this);
            } else if (parent.leftChild == this) {//left node is the only one child node
                parent.leftChild = (leftChild != null) ? leftChild : rightChild;
            } else if (parent.rightChild == this) {//right node is the only one child node
                parent.rightChild = (leftChild != null) ? leftChild    : rightChild;
            }
            return true;
        }
    }

    /*
     * The minimum value of a tree is always located in the left sub tree,
     * so recursively search from left subtree. 
     */
    public int minValue() {
        if (leftChild == null)
            return value;
        else
            return leftChild.minValue();
    }

}

class Tree {

    Node root;

    public void insert(Node node) {
        if (root == null) {
            root = node;
        } else {
            Node temp = root;
            while (temp != null) {
                if (node.value >= temp.value) {
                    if (temp.rightChild == null) {
                        temp.rightChild = node;
                        break;
                    } else {
                        temp = temp.rightChild;
                    }
                } else {
                    if (temp.leftChild == null) {
                        temp.leftChild = node;
                        break;
                    } else {
                        temp = temp.leftChild;
                    }

                }
            }

        }
    }

    public boolean remove(int value) {
        if (root == null)
            return false;
        else {
            if (root.value == value) {
                Node auxRoot = new Node(0);
                auxRoot.leftChild = root;
                boolean result = root.remove(value, auxRoot);
                root = auxRoot.leftChild;
                return result;
            } else {
                return root.remove(value, null);
            }
        }
    }

    public void preOrderTraversal(Node root) {
        System.out.println(root.value);
        if (root.leftChild != null) {
            preOrderTraversal(root.leftChild);
        }
        if (root.rightChild != null) {
            preOrderTraversal(root.rightChild);
        }
    }

}

BST with c++

2012年5月22日 星期二

BFS implementation using queue and adjacency list

package graph;

import java.util.LinkedList;
import java.util.Queue;



public class BFS {
    
    public static int graph [][] = {
        {1,2},//0
        {0,3,4},//1
        {0,5,6},//2
        {1,7},//3
        {1,7},//4
        {2,7},//5
        {2,7},//6
        {3,4,5,6}//7
    };
    
    static Queue outPut = new LinkedList();
    static int visited [] = {-1,-1,-1,-1,-1,-1,-1,-1};//Initialize all unvisited.
    
    public static int [] findNeighbours(int v){
        return graph[v];
    }
    
    public static boolean isVisited(int v){
            if(visited[v]==1){
                return true;
            }else{
                return false;
            }
    }
    
    public static void main(String[] args) throws InterruptedException{
        outPut.offer(0);
        while(!outPut.isEmpty()){
            int vertex = (Integer)outPut.poll();
            if(!isVisited(vertex)){
                visited[vertex]=1;
                System.out.print(vertex);
                int neighbours []= findNeighbours(vertex);
                for(int i = 0 ;i<neighbours.length;i++){
                    if(!isVisited(neighbours[i])){
                        outPut.offer(neighbours[i]);
                    }
                }
                
            }
            
        }
        
        
    }
    

}

2012年5月21日 星期一

Directed Graph Traversal using recursive DFS



import java.util.Stack;

public class RecursiveDFS {

    public static int graph[][] = {

            { 1, 2 },// 0

            { 0, 3, 4 },// 1

            { 0, 5, 6 },// 2

            { 1, 7 },// 3

            { 1, 7 },// 4

            { 2, 7 },// 5

            { 2, 7 },// 6

            { 3, 4, 5, 6 } // 7

    };

    static int visited[] = { -1, -1, -1, -1, -1, -1, -1, -1 };// Initialize all
                                                                // unvisited.

    public static int[] findNeighbours(int v) {

        return graph[v];

    }

    public static boolean isVisited(int v) {
        if (visited[v] == 1)
            return true;
        else
            return false;
    }

    public static void recursiveDFS(int vertex) {
        System.out.print(vertex);
        visited[vertex] = 1;
        int neighbours[] = findNeighbours(vertex);
        for (int i = 0; i < neighbours.length; i++) {
            if (!isVisited(neighbours[i])) {
                recursiveDFS(neighbours[i]);
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        recursiveDFS(0);
    }

}

DFS(Depth First Search) using a stack with adjacency list



import java.util.Stack;



import sun.misc.Queue;



public class DFS {

   

    public static int graph [][] = {

        {1,2},//0

        {0,3,4},//1

        {0,5,6},//2

        {1,7},//3

        {1,7},//4

        {2,7},//5

        {2,7},//6

        {3,4,5,6}//7

    };

   

    static Stack stack = new Stack();

    static Queue outPut = new Queue();

    static int visited [] = {-1,-1,-1,-1,-1,-1,-1,-1};//Initialize all unvisited.

   

    public static int [] findNeighbours(int v){

        return graph[v];

    }

   

    public static boolean isVisited(int v){

            if(visited[v]==1){

                return true;

            }else{

                return false;

            }

    }

   

    public static void main(String[] args) throws InterruptedException{

        stack.push(0);

        while(!stack.empty()){

            int vertex = (Integer)stack.pop();

            if(!isVisited(vertex)){

                visited[vertex]=1;

                outPut.enqueue(vertex);

                int neighbours []= findNeighbours(vertex);

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

                    if(!isVisited(neighbours[i])){

                        stack.push(neighbours[i]);

                    }

                }

               

            }

           

        }

       

        while(!outPut.isEmpty()){

            System.out.print(outPut.dequeue());

        }

       

    }

   

   



}



BFS

2012年5月17日 星期四

Triangle Printing(三角形列印)

Following code segments will print a triangle


public class TriangleDemo {
    /**
     * printing following triangle:
     *       *
     *      **
     *     ***
     *    ****
     *   *****     
     * 
     */
    
    public static void main(String[]args){
        int level = 5;
        for(int i = level ; i > 0 ; i--){
            for(int blank = i-1 ; blank > 0  ;blank--){
                    System.out.print(" ");
            }
            for(int star = i ;star <= level ; star++){
                System.out.print("*");    
            }
            System.out.println("\n");
        }
        
    }

}

2012年5月16日 星期三

Java Stack class

在實做演算法的時候,常會用到stack(堆疊),這個資料結構.

Java便提供了此方法如下:


import java.util.Stack;


public class StackDemo {
    
    public static void main(String [] args){
        Stack stack = new Stack();
        stack.push(1);
        stack.push(2);
        while(!stack.empty()){
            System.out.println(stack.pop());
        }
    }

}

2012年5月6日 星期日

Solvaing Maze Traversal problems with a Brute-Force algorithm

/*
 * Hello.c
 *
 *  Created on: 2012/5/5
 *      Author: Administrator
 */
#include <stdio.h>
#include <stdlib.h>
#define startRow 2
#define startCol 0
#define endRow 5
#define endCol 7

void mazeTraverse(char [][8], int , int , char);
void printMaze(char[][8]);
#include <stdlib.h>
#include <stdio.h>
int main(void){
    char maze [][8]={
            {'#','#','#','#','#','#','#','#'},
            {'#','.','.','#','#','#','#','#'},
            {'.','.','#','#','.','#','#','#'},
            {'#','.','#','#','.','#','#','#'},
            {'#','.','#','#','.','#','#','#'},
            {'#','.','.','.','.','.','.','.'},
            {'#','.','#','.','#','#','.','#'},
            {'#','#','#','#','#','#','#','#'},

    };
    mazeTraverse(maze, startRow, startCol, 's');
    printMaze(maze);
    return 0;
}
void mazeTraverse(char maze[][8], int r, int c, char d) {
    maze[r][c] = 'X';
    if(r == endRow && c == endCol){
            return;
    }else{
            if ('n' == d) {
                if (maze[r][c + 1] != '#') {
                    mazeTraverse(maze, r, c+1, 'w');
                } else if (maze[r - 1][c] != '#') {
                    mazeTraverse(maze, r-1, c, 'n');
                } else if (maze[r][c + 1] != '#') {
                    mazeTraverse(maze, r, c+1, 'e');
                } else {
                    mazeTraverse(maze, r+1, c, 's');
                }
            }

            if ('e' == d) {
                if (maze[r - 1][c] != '#') {
                    mazeTraverse(maze, r-1, c, 'n');
                } else if (maze[r][c + 1] != '#') {
                    mazeTraverse(maze, r, c+1, 'e');
                } else if (maze[r + 1][c] != '#') {
                    mazeTraverse(maze, r+1, c, 's');
                } else {
                    mazeTraverse(maze, r, c-1, 'w');
                }
            }

            if ('s' == d) {
                if (maze[r][c + 1] != '#') {
                    mazeTraverse(maze, r, c+1, 'e');
                } else if (maze[r + 1][c] != '#') {
                    mazeTraverse(maze, r+1, c, 's');
                } else if (maze[r][c - 1] != '#') {
                    mazeTraverse(maze, r, c-1, 'w');
                } else {
                    mazeTraverse(maze, r-1, c, 'n');
                }
            }

            if ('w' == d) {
                if (maze[r + 1][c] != '#') {
                    mazeTraverse(maze, r+1, c, 's');
                } else if (maze[r][c - 1] != '#') {
                    mazeTraverse(maze, r, c-1, 'w');
                } else if (maze[r - 1][c] != '#') {
                    mazeTraverse(maze, r-1, c, 'n');
                } else {
                    mazeTraverse(maze, r, c+1, 'e');
                }
            }
    }

}

void printMaze(char maze[][8]) {
    int i, j;
    for (i = 0; i < 8; i++) {
        for (j = 0; j < 8; j++) {
            printf("%c", maze[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}

2012年3月25日 星期日

Merge Sort (合併排序法)


package sort;

public class MergeSortDemo {


public static void main(String[] args) {
int[] array = { 3, 3,2,1,0,4,5,1,4};
array = mergeSort(array);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}

public static int[] mergeSort(int[] list) {
//if merely left 1 element return list;
if (list.length <= 1) {
return list;
} else {
int[] left;
int[] right;
int middle = list.length / 2;
//declare left sub array;
left = new int[middle];
//declare right sub array;
right = new int[list.length - middle];
int j = 0;
for (int i = 0; i < list.length; i++) {
if (i < left.length) {
//initialize left array
left[i] = list[i];
} else {
//initialize right array
right[j] = list[i];
j++;
}
}
//divide left array into small parts;
left = mergeSort(left);
//divide right array into small parts;
right = mergeSort(right);
//combine small parts of left and right
return merge(left, right);
}
}

public static int[] merge(int[] left, int[] right) {
int[] result = new int[left.length + right.length];
int j = 0;
while (left.length > 0 || right.length > 0) {
//left and right array have elements.
if (left.length > 0 && right.length > 0) {
if (left[0] <= right[0]) {
result[j] = left[0];
left = shiftArray(left);
} else {
result[j] = right[0];
right = shiftArray(right);
}

} else if (left.length > 0) {
//left array has elements;
result[j] = left[0];
left = shiftArray(left);
} else if (right.length > 0) {
//right array has elements;
result[j] = right[0];
right = shiftArray(right);
}
j++;
}
return result;
}

private static int[] shiftArray(int[] i) {
int[] result = new int[i.length - 1];
for (int j = 0; j < result.length; j++) {
result[j] = i[j+1];
}
return result;
}
}




Reference Wiki

2012年3月24日 星期六

Recursive Selection Sort (遞迴選擇排序法)

維護舊有Java程式專案
1:  public class RecursiveSelectionSort {  
2:      public static void main(String[] args) {  
3:          int [] array ={5,2,3,6,1,7,0,9,100,4,8};  
4:          selectionSort(array, array.length);  
5:          for(int i=0;i<array.length;i++){  
6:              System.out.print(array[i]+" ");  
7:          }  
8:      }  
9:      /**  
10:       * Using the concept of selection sort.  
11:       * Implemented by an iterative and a recursive mechanisms.  
12:       *   
13:       * Following are steps:  
14:       * 1.Finding the smallest one and its index;  
15:       * 2.Put the smallest into the right end side;  
16:       * 3.Decrease the array size;  
17:       * Recursively calling this method.  
18:       *   
19:       * @param array unsorted array  
20:       * @param length array length  
21:       */  
22:      public static void selectionSort(int[] array , int length) {  
23:          if(length > 0){  
24:              int smallestIdx = 0 ;  
25:              int smallest = array[smallestIdx];  
26:              //1.From left to right find the smallest one and its index;  
27:              for(int i =0 ;i<length ;i++){  
28:                  if(array[i]< smallest){  
29:                      smallest = array[i];  
30:                      smallestIdx = i;  
31:                  }  
32:              }  
33:              //2.Put the smallest into the right end side;  
34:              swapElements(array,smallestIdx,length -1);  
35:              //3.Decrease the array size;  
36:              length -=1;  
37:              //4.Recursively calling this method.  
38:              selectionSort(array,length);  
39:          }  
40:      }  
41:      private static void swapElements(int[] array, int idx, int idx1) {  
42:          int tmp = array[idx];  
43:          array[idx] = array[idx1];  
44:          array[idx1] = tmp;  
45:      }  
46:  }  

2012年3月23日 星期五

Binary Search (Recursive version)

Before you do binary search, you should sort the unsorted elements first 在使用binary搜尋之前, 要先把資料排序過. Sort(排序)

public class BinarySearch {
 
 public static void main(String [] args){
  int [] i ={2,3,4,4,5,6,7,87};
  System.out.println(binarySearch(i,0,i.length-1,5));
  
 }
 
 public static int binarySearch(int[] i, int left, int right, int target) {
  int middle = (left+right)/2;
  if (i[middle] == target) {
   return middle;
  } else if (i[middle] > target) {
   return binarySearch(i,left,middle,target);
  } else{
   return binarySearch(i,middle,right,target);
  }
 }
}



A c++ binary search tree

Iterative and Recursive

2012年2月27日 星期一

Dynamic Programming(動態程式規劃)

Dynamic Programming : 主要概念是把複雜的大問題,切割成多個小問題,然後把這些小問題的答案組合出一個較完成的答案, 來解答大問題. 若列舉出所有答案的排列組合,很花時間而且會做很多多餘且重複不必要的計算, 使用動態程式設計可以減少許多不必要的計算時間和次數.

以下用找出陣列元素總合為最大值的子陣列來做解釋

Maximum Subarray Problem:






2011年9月10日 星期六

c語言二維加法

先把10進位整數轉換為2進位,然後做2進位的加法運算;
2進為加法運算的概念是.
ie.11
101
+ 11
========
1000
1+1=2=1*2+0,,,c=1,, s=0;s代表相加後最右邊的位元,而c代表進位值
0+1+c=0+1+1=2=1*2+0;同理c1=1,s1=0;
1+1=2=1*2+0, c2=1, s=0
以下是運算的程式碼

進位轉換程式-C語言

利用除法求餘數的概念來寫的

行程安排應用程式

2011年9月9日 星期五

next permutation

next permutation的問題是說,假設有一組數字,希望找出大於這組數字的最小數字的排列組合.

2011年8月12日 星期五

字串搜尋演算法-String Matching Horspool

這個演算法在長字串搜尋的時候,特別有效率.

2011年7月14日 星期四

演算法分析(Algorithm Analysis)


如何判別一個程式寫得好不好,可以用這個程式需要花費的記憶體,或是說要花多少時間才能解出答案,來判斷.因為現在硬體的價格很大眾化.所以我們可以專注在,時間上的討論. 有一個叫做Big-O的概念: 因為會影響時間的因素很多,因此這個概念主要是以討論程式執行的次數多寡來決定要花多少時間.一般我們都是採取比較嚴格的標準檢視程式,所以主要都是討論,在最差的情形下,這程式要花多少時間找出答案.


比如說

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

}


假如答案在最後一項,迴圈要跑到n-1,也就是最後一個才找到答案,我們用O(n),來表示這個迴圈要花線性時間來找出答案.
又如


answer=n*2;


因為答案只需要一次就找出來了,我們用O(1)來表示程式只需要常數時間就會找到答案
又若我們可以把數字排序後再來找答案,那麼所需要的時間只有一半而已.
假設1,2,3,4,用Binary Search只需要1~2次即可找出答案,所以可以用O(logN)
來表示只要對數的時間即可找出答案. 我們可以這麼去想, 4=2^2 ,以2為基底的log: log4=2;
所以把線性時間乘以2為基底的log,即為log N.

2011年7月11日 星期一

軼代和遞迴Iterative and Recursive

遞迴的整體概念是把同樣類似重複的工作,分拆到最小的單位來做,然後慢慢把小單位的結果集合成大單位的結果,然後成為答案.
遞迴要有兩個要素:1.基本元素,也可說是終止條件 2.遞迴判斷條件,
例如:2^0 =1; 2^1=2*2^0; 2^2=2*2^1, 2^3=2*2^2,到最後我們可以歸納為
x^0=1,這個就是基本條件, 又若n>0的話, x^n=x*x^n-1;這個就是遞迴條件.
以下是以n的幾次方分別用用遞迴和軼代的方式來實作的程式碼:


#include <iostream>
using namespace std;

int recursive(int, int);

int main() {
cout << recursive(2,3);
return 0;

}

int recursive(int x, int n){
if(n==0){
return 1;
}else{
return x*recursive(x, n-1);
}
}






所有的遞迴和Iterative都可以互換,跑出同樣的結果,把上列程式用Iterative來寫變成:


#include <iostream>
using namespace std;

int recursive(int, int);

int main() {
cout << recursive(2, 3);
return 0;

}

int recursive(int x, int n) {
int answer=1;
if (n==0) {
return answer;
} else {
for (int i=0; i<n; i++) {
answer *=x;
}
}
return answer;
}




但遞迴較佔記憶體空間.

divide and conquer with recursive


遞迴常被使用在分割-處理的使用上,很多二分(Binary)相關的演算法都是用recursive實作

2011年7月8日 星期五

Linear Search in C++(C++實作線性搜尋)

使用Recursion來實作C++快速排序法(Quick Sort)




其他排序法Other sort algorithm.
Selection Sort

Selection Sort in C++

來過請留下痕跡,無論是留言,給建議或是點閱有興趣的廣告
都是支持繼續寫網誌的動力.



The complexity of selection sort is O(n^2)
selection sort(選擇排序)的基本概念是,找出最大或最小的數字,放在最左邊,然後再從剩下的數字中,找出最大或最小的值,依次由左到右放,直到所有的數字都檢查過為止.





other sort algorithms:
Quick Sort