算法基础
队列:先进先出,后进后出
public class dui {
private Object[] objects;
private int size;
private int head;
private int end;
public dui(int size){
this.objects = new Object[size];
this.head = 0;
this.end = 0;
this.size = 0;
}
public void push(Object object) throws Exception{
if(this.size>objects.length)
throw new Exception("Queue is full");
objects[end++] = object;
size++;
}
public Object pop()throws Exception{
if(this.size == 0)
throw new Exception("Queue is empty!");
if(head == objects.length)
this.head = 0;
size--;
return objects[head++];
}
public Object peek() throws Exception{
if(this.size == 0)
throw new Exception("Queue is empty!");
return objects[head];
}
}
栈:先进后出,后进先出
public class Stack {
private Object[] objects;
private int head;
private int size;
public Stack (int size){
objects = new Object[size];
this.head = 0;
this.size = 0;
}
public void push(Object object) throws Exception{
if (this.size == objects.length)
throw new Exception("this stack is full");
objects[head++] = object;
size++;
}
public Object pop() throws Exception{
if (size == 0)
throw new Exception("this stack is empty");
size--;
return objects[--head];
}
}
斐波那契数列两种实现:递归和非递归
public class feibo {
private static int getFibo(int i){
if (i==1) return 1;
if (i==2) return 1;
else
return getFibo(i-1)+getFibo(i-2);
}
public static void main(String[] args){
for(int j=1;j<=20;j++){
System.out.print(getFibo(j)+"\t");
if(j % 5 == 0)
System.out.println();
}
}
}
冒泡排序
public class mao {
public static void main(String[] args) {
int[] f={3,5,7,12,9,13,14};
int a;
for(int i=0;i<f.length;i++){
for(int j=0;j<f.length-i-1;j++){
if(f[j]<f[j+1])
{
a=f[j];
f[j]=f[j+1];
f[j+1]=a;
}
}
}
System.out.print("最终循环结果" + " ");
for (int i : f) {
System.out.print(i + " ");
}
}
}
快速排序
public class Array {
public static int partition(int []array,int lo,int hi){
int key=array[lo];
while(lo<hi){
while(array[lo]<=key&&hi>lo){
lo++;
}
array[hi]=array[lo];
while(array[hi]>=key&&hi>lo){
hi--;
}
array[lo]=array[hi];
}
array[hi]=key;
return hi;
}
public static void sort(int []array,int lo,int hi){
if(lo>=hi){
return;
}
int index =partition(array,lo,hi);
sort(array,lo,index-1);
sort(array,index+1,hi);
}
public static void main(String[] args) {
int []array={49,27,97,76,13,65,38};
sort(array,0,array.length-1);
for(int i:array){
System.out.print(i+" ");
}
}
}