本文使用java实现了一些常用的算法,包括:冒泡排序 ,分治法快速排序, 选择排序 ,插入排序 ,生成斐波那契数列,滑动窗口查找 ,二分查找有序数组 ,希尔排序,并且会持续更新。代码已上传至github和gitee上,本文为原创文章,引用请注明出处。
- 冒泡排序
public static void bubbleSort(Integer[] arr){
System.out.println("Before sorted: "+ Arrays.toString(arr));
int temp;
for(int i=0;iarr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.println("After sorted: "+ Arrays.toString(arr));
}
- 分治法快速排序
public static void quickSort(Integer[] arr, int low, int high){
if(low>high)
return;
//选中一个基准,按基准分割大小
int pivot = arr[high];
int temp = 0;
int pivotIndex = low;
for(int i=low;i
- 选择排序,选出每个位置上属于该位置的数字
public static void selectionSort(Integer[] arr){
int temp = 0;
for(int i=0;iarr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
- 插入排序,每次插入一个数字进行排序
public static void insertSort(Integer[] arr){
int temp = 0;
for(int i=1;iarr[i]){
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
- 生成斐波那契数列
public static int[] generateFiboArr(int length){
int[] arr = new int[length];
for(int i=0;i
- 滑动窗口查找
public static boolean shiftSearch(@NotNull String str, @NotNull String needFind){
int start = 0;
int end=needFind.length();
String temp = null;
while(end
- 二分查找有序数组
public static boolean binarySearch(Integer[] arr, int needFind){
int start = 0;
int end = arr.length-1;
int index = end/2;
while(index>=1 && index<=(arr.length-1)){
if(arr[index] == needFind){
return true;
}else if(arr[index] < needFind){
start = index;
}else{
end = index;
}
index = (start+end)/2;
}
return false;
}
- 希尔排序,分辨率越低数组越有序
public static void shellSort(double[] arr, int resolution){
int length = arr.length;
double temp = 0d;
while(resolution>0){
for(int i=resolution;i=resolution;j-=resolution){
temp=arr[j];
if(arr[j-resolution]>temp){
arr[j] = arr[j-resolution];
arr[j-resolution] = temp;
}
}
}
}
}



