1、递归
package com.算法1; public class 递归 { public static String daoxu(String str){ if(str == null || str.length() < 2){ return str; } String temp = str.substring(1,str.length()); char end = str.charAt(0); return daoxu(temp) + end; } public static void main(String[] args) { String str = "abcd"; String temp = daoxu(str); System.out.println(temp); } }
2、冒泡
package com.算法1; public class 冒泡 { public static int[] maopao(int arry[]){ for(int i = 0 ; i < arry.length ; i++){ for(int j = i+1 ; j < arry.length ; j++){ if(arry[i] > arry[j]){ int temp = arry[i]; arry[i] = arry[j]; arry[j] = temp; } } } return arry; } public static void main(String[] args) { int [] arry = {6,8,1,11,22,56,33,23,66,12}; maopao(arry); for(int i = 0 ; i < arry.length; i++){ System.out.println(arry[i]); } } }
3、二分查找
package com.算法1; public class 二分查找 { //找出值等于num的下标 public static int erfenchaozhao(int arry[], int num){ int low = 0; int heigh = arry.length - 1; int middle = 0; while(low < heigh){ middle = (low + heigh)/2; if(arry[low] < num){ low ++; }else if(arry[heigh] > num){ heigh--; }else{ return middle; } } return middle; } public static void main(String[] args) { int [] arry = {1,3,4,5,7,9,10,12,15,18,30,60}; int index = erfenchaozhao(arry,12); System.out.println(index); } }
4、快速排序
package com.算法1;
public class 快速排序 {
/**
* 通过一趟排序将要排序的数据分割成独立的两部分,
* 其中一部分的所有数据都比另外一部分的所有数据都要小,
* 然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,
* 以此达到整个数据变成有序序列
*/
static void quicksort(int arry[], int left, int right) {
int dp;
if (left < right) {
dp = partition(arry, left, right);
System.out.println(dp+".....");
quicksort(arry, left, dp - 1);
quicksort(arry, dp + 1, right);
}
}
static int partition(int arry[], int left, int right) {
int pivot = arry[left];
while (left < right) {
while (left < right && arry[right] >= pivot)
right--;
if (left < right)
arry[left++] = arry[right];
while (left < right && arry[left] <= pivot)
left++;
if (left < right)
arry[right--] = arry[left];
}
arry[left] = pivot;
return left;
}
public static void main(String[] args) {
int [] arry = {16,8,21,1,15,56,33,23,66,12};
int left = 0;
int right = arry.length - 1;
quicksort(arry, left, right);
for(int i = 0 ; i < arry.length ; i++){
System.out.println(arry[i]);
}
}
}