/**
* 冒泡排序法(默认升序)
*
* @param array
* 要排序的数组
* @return
*/
public static int[] bubbleSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
return array;
}
/**
* 选择排序法
*
* @param array
* @return
*/
public static int[] selectSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] >= array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array;
}
/**
* 二分查找
* @param array
* @param x
* @return
*/
public static int binaryFind(int[] array, int x) {
int max = array.length - 1;
int min = 0;
int med =0;
while (min <= max) {
med = (max + min) / 2;
if (array[med] > x) {
max = med - 1;
}else if (array[med] < x) {
min = med + 1;
}else {
return med;
}
}
return -1;
}
/**
* 打印数组的工具
*
* @param array
*/
public static void printArray(int[] array) {
System.out.print("[");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if (i >= array.length - 1) {
System.out.print("]");
} else {
System.out.print(",");
}
}
}
转载于:https://my.oschina.net/u/3730650/blog/1629086