常用算法
2016-07-20 15:57
381 查看
插入排序
冒泡排序
二分查找(循环)
二分查找(递归)
数组倒序
public static void main(String[] args) { int a[] = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51 }; int temp = 0; int j = 0; for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) { temp = a[i]; for (j = i - 1; j >= 0 && a[j] > temp; j--) { a[j+1]=a[j]; } a[j+1] = temp; } } for(int k:a){ System.out.print(k+","); } }
冒泡排序
int a[] = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51 }; for(int i=0;i<a.length-1;i++){ for(int j=i;j<a.length-i-1;j++){ if(a[j]>a[j+1]){ int temp = a[j]; a[j]=a[j+1]; a[j+1] = temp; } } } for(int k:a){ System.out.print(k+","); } }
二分查找(循环)
public static void main(String[] args) { int a[] = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51 }; for(int i=0;i<a.length-1;i++){ for(int j=i;j<a.length-i-1;j++){ if(a[j]>a[j+1]){ int temp = a[j]; a[j]=a[j+1]; a[j+1] = temp; } } } int low = 0; int high = a.length-1; while(low<=high){ int mid = (low+high)/2; if(78==a[mid]){ System.out.print("数组位置:"+mid); break; } else if(78<a[mid]){ high = mid-1; } else{ low = mid+1; } } }
二分查找(递归)
private static int halfSearch(int[] a,int low,int high,int target){ if(low>high){ return -1; } else{ int mid = low+high; if(target == a[mid]){ return mid; } else if(target < a[mid]){ return halfSearch(a,low,mid-1,target); }else return halfSearch(a,mid+1,high,target); } }
数组倒序
public static void main(String[] args) { int a[] = { 1,2,45,78,56,22}; for(int i =0;i<a.length/2;i++){ int k = a[i]; a[i]=a[a.length-i-1]; a[a.length-i-1]=k; }
相关文章推荐
- 插入排序
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#递归算法之分而治之策略
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#算法之大牛生小牛的问题高效解决方法
- C#算法函数:获取一个字符串中的最大长度的数字
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 经典排序算法之冒泡排序(Bubble sort)代码
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法