二分法 冒泡
2016-01-26 05:28
232 查看
二分法
public class MyArrays{ public static void main(String[] args){ int[] a = {1,3,4,5,7,8,9,10,23,25,29}; // 取得23在数组中的位置 int flag = 53; int index = binarySearch(a,flag); if(index != -1){ System.out.println("取得数组中"+flag+" 的下标为:" + index); } else { System.out.println("该值:"+flag+" 在数组中不存在 !"); } } // 采用二分法查找,必须建立在排序的基础之上 public static int binarySearch(int[] a,int flag){ // 开始下标0 int beginPos = 0; // 结束下标 int endPos = a.length - 1; while(beginPos <= endPos){ int midPos = (beginPos + endPos) / 2; if(flag == a[midPos]){ return midPos; } else if(flag > a[midPos]){ beginPos = midPos + 1; } else if(flag < a[midPos]){ endPos = midPos - 1; } } return -1; } }冒泡
public static void sort(Object []arr){ boolean sorted=true; int len= arr.length; for(int i =0;i<len-1;i++){ sorted=true; for(int j =0;j<len-i-1;j++){ if((Comparable)arr[j].compareTo(arr[j+1])<0){ Object temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; sorted=false; } } } if(sorted){break;} }
相关文章推荐
- find Minimum and Maximum in Rotated Sorted Arrray
- Codeforces Round #328 (Div. 2) 592 D. Super M 树的直径
- Codeforces Round #328 (Div. 2) 592 C. The Big Race
- 关于鸣人发招
- ansible官方文档翻译之变量
- ansible官方文档翻译之变量
- Codeforces Round #328 (Div. 2) 592 B. The Monster and the Squirrel
- Codeforces Round #328 (Div. 2) 592A PawnChess
- Osmocom-BB多信道修改代码相关
- C118 免按开机自动加载固件
- 关于清除浮动
- POJ1651:Multiplication Puzzle(区间DP)
- POJ2955:Brackets(区间DP)
- 前端试题-两列等高布局
- *Check whether a given graph is Bipartite or not
- 小娜学法(17):如何获取案件信息?
- MongoDB Aggregate Methods(2) MonoDB 的 3 种聚合函数
- 输出螺旋矩阵
- 03-构造可靠数据传输协议
- 02-topdown