几种常见算法的JAVA实现
2010-09-09 22:51
513 查看
最近有朋友去应聘,对方给了几个关于算法方面的编程题,我的朋友很惭愧的说,有些真的不记得了。我问了下自己,得到的答案是,我也要好好温习下十年前的功课了,真是愧对老师啊。耗了两个钟才写了下面这些东东,主要是二分查找,插入排序,冒泡排序。另外,考官还问了时间复杂度的问题,比较了算法的优劣。
二分查找
插入排序
冒泡排序
二分查找
import java.util.Arrays; class MidSearch { public static int getIndexByMid(char[] array,char key) { int low = 0; int high = array.length; while (low <= high) { int mid = (low + high) / 2; if (array[mid] < key) low = mid + 1; else if (array[mid] > key) high = mid - 1; else { return mid; } } return -1; //未找到,返回-1 } public static void main(String[] args) { char[] ch="ert13aco27".toCharArray(); Arrays.sort(ch); String str = new String(ch); System.out.println("index of the character in the String "+str+" is "+getIndexByMid(ch,'o')); } }
插入排序
class InsertSt { static char[] insertSort(char[] ch)//直接插入排序 { for(int i=1;i<ch.length;i++) { char temp=ch[i]; int j=0; for(j=i;j>0&&temp<ch[j-1];j--) { ch[j]=ch[j-1];//ch[j-1]推到原来ch[j]的位置,依次往后类推。 } ch[j]=temp;//在空出的原来ch[j-1]的位置上放置tmp,即ch[i]。 } return ch; } public static void main(String[] args) { char[] ch="ert13aco27".toCharArray(); System.out.println(insertSort(ch)); } }
冒泡排序
class BubbleSort { public static void bubbleSort(char[] arry) { int len = arry.length; for (int i = 0; i < len; i++) { //boolean asc = true; for (int j = 1; len - i > j; j++) { if (arry[j] < arry[j - 1]) { swap(arry, j, j - 1); //asc = false; } } //if (asc) return; } } private static void swap(char[] arry, int i, int j) { char temp = arry[i]; arry[i] = arry[j]; arry[j] = temp; } public static void main(String[] args) { char[] temp="rckf9yss1v2".toCharArray(); BubbleSort bs = new BubbleSort(); bs.bubbleSort(temp); System.out.println(temp); } }
相关文章推荐
- 几种常见排序算法之Java实现(插入排序、希尔排序、冒泡排序、快速排序、选择排序、归并排序)
- 几种常见的排序算法Java实现总结
- 常见算法的java实现代码(持续更新中)
- 在Java中利用Apache Commons Codec API实现常见的加密解密算法,如:md5,sha256
- JAVA常见的权限控制算法的实现[转]
- 数据结构--Java实现几种常见排序
- JAVA常见的权限控制算法的实现
- Java实现几种常见排序方法
- 常见算法学习及其Java实现--有序区和无序区的冒泡算法实现
- java中常见的几种排序实现
- 用Java实现几种常见的排序算法
- Java实现几种常见排序方法
- 用Java实现几种常见的排序算法及SortUtil
- Java实现几种常见排序方法(上)
- Java实现几种常见排序方法
- Java实现几种常见排序方法(上)
- 用Java实现几种常见的排序算法
- Java实现几种常见排序方法
- 常见算法学习及其Java实现--冒泡算法实现
- 负载均衡的几种算法Java实现代码