标题: 冒泡排序法、选择排序法、二分查找法 [打印本页] 作者: ljd 时间: 2016-6-3 20:19 标题: 冒泡排序法、选择排序法、二分查找法 public class ArraysUtil {
/*
* 遍历数组
*/
public static void arrayToString(int[] numbers){
System.out.print("[");
for (int i = 0; i < numbers.length; i++) {
if(i == numbers.length - 1){
System.out.print(numbers[i]);
}else {
System.out.print(numbers[i] + ",");
}
}
System.out.print("]\n");
}
/*
* 冒泡排序法
*/
public static void bubbleSort(int[] numbers) {
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = 0; j < numbers.length - 1 - i; j++) {
if(numbers[j] > numbers[j+1]){
int temp = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = temp;
}
}
}
}
/*
* 选择排序法
*/
public static void selectSort(int[] numbers) {
for (int i = 0; i < numbers.length- 1; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if(numbers[i] > numbers[j]){
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
}
/*
* 基本查找法
*/
public static int getIndex(int[] numbers, int value){
int index = -1;
for (int i = 0; i < numbers.length; i++) {
if(numbers[i] == value){
index = i;
break;
}
}
return index;
}
/*
* 二分查找法
*/
public static int binarySearch(int[] numbers, int value){
int min = 0;
int max = numbers.length - 1;
int mid = (min+max)/2;
while(numbers[mid] != value){
if(numbers[mid] > value){
max = mid - 1;
}else if (numbers[mid] < value) {
min = mid + 1;
}
if(min > max){
return -1;
}
mid = (min+max)/2;
}
return mid;
} 作者: 学渣一枚 时间: 2016-6-3 20:30
赞赞赞赞赞赞赞赞赞赞赞赞赞赞赞赞赞赞赞赞赞赞