锦上添花,无锦无花
选择排序
public class NumSort {
public static void main(String[] args) {
int[] a = new int[args.length];
for(int i=0; i<args.length; i++) {
a[i]=Integer.parseInt(ar]);
}
print(a);
}
private static void print(int[] a) {
for(int i= 0; i<a.length; i++) {
System.out.println(a[i]+" ");
}
}
}
注意 2 3 1 之间空格
冒泡排序
public class TestDateSort {
public static void main(String[] args) {
Date[] days = new Date[5];
days[0] = new Date(2006, 5, 4);
days[1] = new Date(2006, 7, 4);
days[2] = new Date(2008, 5, 4);
days[3] = new Date(2004, 5, 9);
days[4] = new Date(2004, 5, 4);
bubbleSort(days);
for(int i=0; i<days.length; i++) {
System.out.println(days[i]);//打印一个对象的引用相当调用toString方法
}
}
public static Date[] bubbleSort(Date[] a) {
int len = a.length;
for(int i = len-1; i>=1; i--) {
for(int j = 0; j<=i-1; j++) {//a[0]和a[1]比,a[1]和a[2]比,依次类推,谁大谁下移
if(a[j].compare(a[j+1]) > 0) {
Date temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
return a;
}
}
class Date {
int year, month, day;
Date(int y, int m, int d) {
year = y; month = m; day = d;
}
public int compare(Date date) {
return year > date.year ? 1
: year < date.year ? -1//相等比较month
: month > date.month ? 1
: month < date.month ? -1
: day > date.day ? 1
: day < date.day? -1 : 0;
}
public String toString() {
return "Year:Month:Day-- "+ year + "-" +month + "-" + day;
}
}
数3退1
500个小孩子手拉手围成一圈.数到3,退出一个人后,继续数。直到只有一个人,最后一个人在哪
public class Count3Quit {
public static void main(String[] args) {
boolean[] arr = new boolean[500];
for(int i=0; i<arr.length; i++) {//初始化
arr[i] = true;
}
int num = 0;
int index = 0;
int leftCount = arr.length;
while(leftCount > 1) {
if(arr[index] == true) {
num ++;
if(num == 3) {//逢三去一
num = 0;
arr[index] = false;
leftCount --;
}
}
index++;
if(index == arr.length) {//虽然把一些数变成了false,但每次要对比500个数
index = 0;
}
}
for(int i=0; i<arr.length; i++) {
if(arr[i] == true) {
System.out.println(i);
}
}
}
}
面向对象
public class Count3Quit2 {
public static void main(String[] args) {
KidCircle kc = new KidCircle(500);
int countNum = 0;
Kid k = kc.first;
while(kc.count > 1) {
countNum ++;
if(countNum ==3) {
countNum = 0;
kc.delete(k);
}
k = k.right;
}
System.out.println(kc.first.id);
}
}//运用面向对象的方法
class Kid {//名词一 小孩
int id;
Kid left;
Kid right;//找其拥有的属性
}
class KidCircle {//名词二 小孩拉成的 圈
int count = 0;
Kid first, last;
KidCircle(int n) {//构造方法b
for(int i=0; i<n; i++) {
add();
}
}
/**void add(Kid k) {//向圈里添加一个小孩,小孩为宾语即为参数
}**/
void add() {
Kid k = new Kid();
k.id = count;
if(count <= 0) {
first = k;
last = k;
} else {
last.right = k;
k.left = last;
k.right = first;
first.left = k;
last = k;
}
count ++;
}
void delete(Kid k) {
if(count <= 0) {
return;
} else if (count == 1) {
first = last = null;
} else {
k.left.right = k.right;
k.right.left = k.left;
if(k == first) {
first = k.right;
} else if( k == last) {
last = k.left;
}
}
count --;
}
}
目录
用 [TOC]
来生成目录: