数组的常用算法
冒泡排序
int[] a1 = {8,3,5,6,9};
for (int i = a1.length-1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (a1[j] > a1[j+1]) {
int temp = 0;
temp = a1[j];
a1[j] = a1[j+1];
a1[j+1] = temp;
}
}
}
选择排序
int[] a2 = {7,8,3,2};
for (int i = 0; i < a2.length-1; i++) {
int min = i;
for (int j = i+1; j < a2.length; j++) {
if (a2[min] > a2[j]) {
min = j;
}
}
if (min!=i) {
int temp = 0;
temp = a2[i];
a2[i] = a2[min];
a2[min] = temp;
}
}
二分法查找(折半查找)
public static int binarySearch(int[] a,int destElement) {
int begin = 0;
int end = a.length-1;
while (begin<=end) {
int mid = (begin+end)/2;
if (a[mid] == destElement) {
return mid;
}else if(a[mid] > destElement) {
end = mid-1;
}else if(a[mid] < destElement) {
begin = mid + 1;
}
}
return -1;
}