队列
public class Queue {
private Object[] objects;
private int size;
private int head;
private int end;
public Queue(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)
// return null;
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 boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == objects.length;
}
public int getSize() {
return size;
}
}
栈
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 Fib {
public int fib(int n){
if(n==1||n==2)
return 1;
if(n>=3)
return fib(n-1)+fib(n-2);
return 0;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Fib fei=new Fib();
System.out.println(fei.fib(n));
}
}
冒泡排序
public class MP {
public static void main(String[] args) {
int a[]= {11,2,5,82,7,0,4,89,72,42,16,34,58,23};
for(int i=0;i<a.length;i++){
int temp = a[i];
for(int j=i+1;j<a.length;j++){
if(a[j] < temp){
a[i] = a[j];
a[j] = temp;
temp=a[i];
}
}
}
for(int x:a){
System.out.println(x);
}
}
}
快速排序
public class QuickSort {
public static int middle(int[] array, int left, int right) {
int temp = array[left];
while (left != right) {
while (right > left && array[right] > temp)
right--;
array[left] = array[right];
while (right > left && array[left] < temp)
left++;
array[right] = array[left];
}
array[right] = temp;
return right;
}
public static int[] sort(int[] a, int left, int right) {
if (left < right) {
int i = middle(a, left, right);
sort(a, left, i);
sort(a, i + 1, right);
}
return a;
}
public static void main(String[] args) {
int[] a = {11, 81, 27, 53, 42, 45, 6, 77, 178, 9, 70};
sort(a, 0, a.length - 1);
for (int i : a) {
System.out.print(i+" ");
}
}
}