java实现各种算法

来源:互联网 发布:菜刀连接数据库 编辑:程序博客网 时间:2024/05/16 12:07
最近复习一下各种算法,把它们写在这里,留着备用,呵呵。
/**

 * 冒泡排序

 * 时间复杂度:O(n^2)

 */
public static void maoPaosort(int[] array) {
for (int i = 1; i < array.length; i++) {
for (int j = 0; j < array.length - i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}

}

/**
* 选择排序
时间复杂度:O(n2)
*/
public static void selectionSort(int[] elements) {
for (int i = 0; i < elements.length - 1; ++i) {
int k = i;
for (int j = i; j < elements.length; ++j) {
if (elements[k] > elements[j]) {
k = j;
}
}
if (k != i) {// 交换元素
int temp = elements[i];
elements[i] = elements[k];
elements[k] = temp;
}
}
}

/**
* 插入排序(直接插入)
时间复杂度:Θ(n^2)
*/
public static void insertSort(int[] elements) {
for (int i = 1; i < elements.length; i++) {
int j = -1;
while (j <= i && elements[i] > elements[++j]) {
}// 找到element[i]应该摆放的位置,此处可以利用查找算法进行优化
if (j < i) {
// 将j之后的数据移动一位,然后把elements[i]移动到j处
int temp = elements[i];
for (int k = i - 1; k >= j; k--) {
elements[k + 1] = elements[k];
}
elements[j] = temp;
}


}
}

/**
* 插入排序(
希尔排序
时间复杂度:O(n)
*/

public static void shellSort(int[] arr){  
        int i,j,n=1,temp,len = arr.length;  
        while(n<=len/3)  
            n = n*3+1;  
        while(n > 0){  
            for (i = n; i < len; i++) {  
                temp = arr[i];  
                j = i;  
                while(j >= n && arr[j - n] >= temp){  
                    arr[j] = arr[j - n];  
                    j-=n;  
                }  
                arr[j] = temp;  
            }  
            n = (n - 1)/3;  
        }  
    } 

/** 快速排序方法

 *时间O(n log n)

*/
public static void quickSort(int[] a, int lo0, int hi0) {
int lo = lo0;//0
int hi = hi0;//6
if (lo >= hi)
return;
boolean transfer = true;
while (lo != hi) {
if (a[lo] > a[hi]) {
int temp = a[lo];
a[lo] = a[hi];
a[hi] = temp;
transfer = (transfer == true) ? false : true;
}
if (transfer)
hi--;
else
lo++;
}
lo--;
hi++;
quickSort(a, lo0, lo);
quickSort(a, hi, hi0);
}



以下为java实现的二叉树:


public class MyBTree {
private Node root;
private MyBTree left;
private MyBTree right;


public void addNode(int n) {
if (root == null) {
root = new Node();
root.setDate(n);
} else {
int data = root.getDate();
if (n <= data) {
if (left == null) {
this.left = new MyBTree();
}
this.left.addNode(n);


} else {
if (right == null) {
this.right = new MyBTree();
}
this.right.addNode(n);


}
}
}


public void printBTree() {
if (left != null) {
left.printBTree();
}
if (root != null) {
System.out.print(root.getDate() + "
,");
}
if (right != null) {
right.printBTree();
}
}


public static void main(String[] args) {
int k[] = { 4, 3, 5, 2, 6, 1, 87, 54 };
MyBTree b = new MyBTree();
for (int i = 0; i < k.length; i++) {
b.addNode(k[i]);
}
b.printBTree();
}
}


class Node {
private int date;


public int getDate() {
return date;
}


public void setDate(int date) {
this.date = date;
}
}


以上代码均来自网络。

原创粉丝点击