冒泡排序
package com.ssc.algorithm;
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] a = {1,52,20,14,13,32,52};
bubblesort(a);
System.out.println(Arrays.toString(a));
}
public static void bubblesort(int[] a) {
int temp;
boolean flag=true;
for(int i=0;i<a.length;i++) {
for(int j=0;j<(a.length-1-i);j++) {
if(a[j]<a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1]=temp;
flag = false;
}
}
if(flag) {
break;
}
}
}
}
二分查找
package com.ssc.algorithm;
public class Dichotomy {
public static void main(String[] args) {
int[] a = {1,5,6,14,16,18,20};
int b = dichotomy(a, 18);
System.out.println(b);
}
public static int dichotomy(int[] a,int b) {
int low = 0;
int high = a.length-1;
while(low<=high) {
int mid = (low+high)/2;
if(b == a[mid]) {
return mid;
}
if(b<a[mid]) {
high = mid-1;
}
if(b>a[mid]){
low=mid+1;
}
}
return -1;
}
}