基础算法
冒泡排序(一);
public class DoubleSort{
public static void main(String[] args){
int[] ints = {1,2,4,9,8,7,6,5,4,3};
doubleSort(ints);
}
public static void doubleSort(int[] vlaue){
int temp;
for(int i = 0;i<value.length;i++){
for(int j= 0;j<value.length-1-i;j++){
if(value[j+1]<value[j]){
temp = value[j];
value[j] = value[j+1];
value[j+1] = temp;
}
}
}
}
}
二分查找:
public class BinarySearch{
public static void main(String[] args){
int ints = {9,2,3,4,5,7,8,1,6,0};
int searchWord = 6;
Arrays.sort(ints);
Arrays.toString(ints);
System.out.println("查找元素的索引是:"+binarySearch(ints,searchWord));
}
public static int binarySearch(int[] array,int value){
int low = 0 ;
int high = array.length-1;
whille(low >= high){
//写成(low+high)/2会数组越界导致内存溢出
int middle = low + (high -low)/2;
if(value == array[middle]){
return middle;
}
if(value > array[middle]){
low = middle +1;
}
if(value < array[middle]){
high = midddle -1;
}
}
return -1;
}
}
数组逆序:
public class Test{
public static void main(String[] args){
int[] ints = {0,9,8,7,6,5,4,3,2,1};
Arrays.toString(ints);
for(int i = 0;i < (int)ints.length/2;i++){
int temp = ints[i];
ints[ints.length-i-1] = ints[i];
ints[i] = temp;
}
for(int i:ints){
System.out.println(i);
}
}
}
使用递归算法,以树状结构展示目录树
public class PrintFile(){
public static void main(String[] args){
//录入文件夹名称
File file = new file("willem")
//调用遍历打印目录树的方法
printFile(file,0);
}
static void printFile(File file,int level){
//遍历层次
for(int i = 0;i<level;i++){
System.out.print("-");
}
//输出文件名称
System.out.println(file.getName());
//声明存放File[]
if(file.isDirectory()){
File[] file = file.listFiles();
for(File file1 : file){
///递归调用该方法:注意层级+1
printFile(file1,level+1);
}
}
}
}