一、一个int类型数组按升序排序案例
public class ArrayTest {
private static int[] arrayAesc;
public static void main(String[] args) {
ArrayTest a = new ArrayTest();
arrayAesc = new int[]{5,2,1,4,6,3};
arrayAesc = a.sortArrayAesc(arrayAesc);
for (int i = 0; i < arrayAesc.length; i++) { System.out.println(arrayAesc[i]);
}
System.out.println("success");
}
public int[] sortArrayAesc(int[] temps){
for (int i = 0; i < temps.length; i++) {
for (int j = i+1; j < temps.length; j++) {
if (temps[i] > temps[j]) {
int temp;
temp = temps[i];
temps[i] = temps[j];
temps[j] = temp;
}
}
}
return temps;
}
}
二、一个int类型数组按降序排序案例
public class ArrayTest {
private static int[] arrayAesc;
public static void main(String[] args) {
ArrayTest a = new ArrayTest();
arrayAesc = new int[]{5,2,1,4,6,3};
arrayAesc = a.sortArrayDesc(arrayAesc);
for (int i = 0; i < arrayAesc.length; i++) { System.out.println(arrayAesc[i]);
}
System.out.println("success");
}
public int[] sortArrayDesc(int[] temps){
for (int i = 0; i < temps.length; i++) {
for (int j = i+1; j < temps.length; j++) {
if (temps[i] < temps[j]) {
int temp;
temp = temps[i];
temps[i] = temps[j];
temps[j] = temp;
}
}
}
return temps;
}
}
三、二分法查找案例
public class TestMiddle {
private final static int target = 1;
private static int findData(int dataset[]){
int dataLength = dataset.length;//获取数组大小
//判断是否存在于数组中
if(dataset[0] > target || dataset[dataLength - 1] < target){
System.out.println("不存在你想要找的数据");
return -1;
}
//获取数组中间那个索引,不过这里要小心,就是数组大小奇数偶数的时候,想一下呵呵
int midIndex = dataLength / 2;
//定义一个中间数组,用来过渡数据
int temp[];
//把中间索引的那个数组值付给这个变量
int midData = dataset[midIndex];
//这就是找到了
if(midData == target){
System.out.println("呵呵,数据已经找到了!!" + midData);
return midData;
}
//中间那个值比目标到的情况
if(midData > target){
//初始化中间数组的长度
temp = new int [midIndex];
for(int i=0;i<midIndex;i++){
temp[i] = dataset[i];
}
return findData(temp);
}
//中间那个值比目标小的时候
if(midData < target){
//最绕的是这里,就是因为奇数偶数....还有向前向后....不再详述
int afterIndex = midIndex;
if(dataLength % 2 == 0){
temp = new int [midIndex-1];
for(int i=0;i<midIndex - 1;i++){
afterIndex = afterIndex + 1;
temp[i] = dataset[afterIndex];
}
}else{
temp = new int [midIndex];
for(int i=0;i<midIndex;i++){
afterIndex = afterIndex + 1;
temp[i] = dataset[afterIndex];
}
}
return findData(temp);
}
else{
System.out.println("不存在你想要找的数据");
return -1;
}
}
public static void main(String[] args) {
int test[] = new int [] {1,2,3,4,5,6,7,8};
TestMiddle.findData(test);
}
}。