摘要:本文主要向大家介绍了JAVA语言实现栈和队列,排序算法代码实例,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。
本文主要向大家介绍了JAVA语言实现栈和队列,排序算法代码实例,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。
java实现栈和队列
栈 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 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; } } Fibonacci public class Fibonacci { public static int f(int n){ if(n<=0)return 0; if(n==1)return 1; if(n==2)return 1; return f(n-1)+f(n-2); } public static void main(String[] args) { //1 1 2 3 5 8 13 //递归 System.out.println(f(8)); //非递归 int n=1; int a=1; int b=1; while (n>2){ int tem=b; b=a+b; a=tem; n--; } System.out.println(b); } } 快速排序 public class QuickSort { public static void sort(int a[], int low, int hight) { int i, j, index; if (low > hight) { return; } i = low; j = hight; index = a[i]; // 用子表的第一个记录做基准 while (i < j) { // 从表的两端交替向中间扫描 while (i < j && a[j] >= index) j--; if (i < j) a[i++] = a[j];// 用比基准小的记录替换低位记录 while (i < j && a[i] < index) i++; if (i < j) // 用比基准大的记录替换高位记录 a[j--] = a[i]; } a[i] = index;// 将基准数值替换回 a[i] sort(a, low, i - 1); // 对低子表进行递归排序 sort(a, i + 1, hight); // 对高子表进行递归排序 } public static void quickSort(int a[]) { sort(a, 0, a.length - 1); } public static void main(String[] args) { int a[] = { 49, 38, 65, 97, 76, 13, 27, 49,5 }; quickSort(a); System.out.println(Arrays.toString(a)); } }
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注编程语言JAVA频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号