您的位置:首页 > 其它

常用算法

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 插入排序