close
http://caterpillar.onlyfun.net/Gossip/JavaGossip-V1/FirstJava.htm
- Java
public class Sort {
public static void selection(int[] number) {
for(int i = 0; i < number.length - 1; i++) {
int m = i;
for(int j = i + 1; j < number.length; j++)
if(number[j] < number[m])
m = j;
if(i != m)
swap(number, i, m);
}
}
public static void insertion(int[] number) {
for(int j = 1; j < number.length; j++) {
int tmp = number[j];
int i = j - 1;
while(i != -1 && tmp < number[i]) {
number[i+1] = number[i];
i--;
}
number[i+1] = tmp;
}
}
public static void bubble(int[] number) {
boolean flag = true;
for(int i = 0; i < number.length-1 && flag; i++) {
flag = false;
for(int j = 0; j < number.length-i-1; j++) {
if(number[j+1] < number[j]) {
swap(number, j+1, j);
flag = true;
}
}
}
}
private static void swap(int[] number, int i, int j) {
int t = number[i];
number[i] = number[j];
number[j] = t;
}
}
循序搜尋法(使用衛兵)
public class Search {
public static int linear(int[] number, int des) {
int[] tmp = new int[number.length + 1];
for(int i = 1; i < tmp.length; i++) {
tmp[i] = number[i-1];
}
tmp[0] = des;
int i = number.length;
while(tmp[i] != tmp[0])
i--;
return i - 1;
}
public static void main(String[] args) {
int[] number = {1, 2, 3, 4, 6, 7, 8};
int find = Search.linear(number, 3);
System.out.println(find >= 0 ? "找到數值於索引" + find : "找不到數值");
}
}
- Jan 29 2012
-
javascript常用函數集
全站熱搜
留言列表