您的位置:首页 > 编程语言 > Java开发

几种常见算法的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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: