三种排序
快排
public class kuaipai {
public static void main(String[] args) {
int arry[] = {23,34,1,43,2,45,27,41};
fastarry(arry,0,arry.length-1);
for(int tmp:arry) {
System.out.println(tmp);
}
}
private static void fastarry(int[] arry, int beindex, int enindex) {
int begin = beindex;
int end = enindex;
int value = arry[beindex];
while(beindex<enindex) {
while(beindex<enindex&&value<=arry[enindex]) {
enindex--;
}
if(value>arry[enindex]) {
int temp = arry[enindex];
arry[enindex] = arry[beindex];
arry[beindex] = temp;
}
while(beindex<enindex&&value>=arry[beindex]) {
beindex++;
}
if(value<beindex) {
int temp = arry[enindex];
arry[enindex] = arry[beindex];
arry[beindex] = temp;
}
}
if(begin<enindex--) {
fastarry(arry,beindex,enindex--);
}
if(end>beindex++) {
fastarry(arry,beindex++,end);
}
}
}
冒泡
public static void soryArraymaopao(int[] arr){
for(int j=arr.length-1;j>0;j--){
for(int i=0;i<j;i++){
if(arr[i]>arr[i+1]){
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
}
}
选择
public static void sortArray(int[] arr){
for(int j=0;j<arr.length-1;j++){
for(int i=j+1;i<arr.length;i++){
if(arr[j]<arr[i]){
int temp= arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
}
}
回文
public class huiwen {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入行:");
int lowC = scan.nextInt();
System.out.println("请输入列:");
int colC = scan.nextInt();
int arr[][] = new int [lowC][colC];
int number= 1;
arr[0][0] = number;
int sum = lowC*colC;
setarray(arr,sum,number,0,0);
for(int[] tmp:arr) {
for(int t:tmp) {
System.out.print(t+"\t");
}
System.out.println();
}
}
private static void setarray(int[][] arr, int sum, int number, int low, int col) {
while(number < sum) {
while(col<arr[low].length-1&&arr[low][col+1]==0) {
arr[low][++col] = ++number;
}
while(low<arr.length-1&&arr[low+1][col]==0) {
arr[++low][col] = ++number;
}
while(col>0&&arr[low][col-1]==0) {
arr[low][--col] = ++number;
}
while(low>0&&arr[low-1][col]==0) {
arr[--low][col] = ++number;
}
}
}
}
二分查找
public class Binary {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7,8,9};
int value = BinarySearch(arr,8,0,arr.length-1);
System.out.println(value);
}
private static int BinarySearch(int[] arr, int find, int begin, int end) {
int mid = (begin+end)/2;
if(begin==end) {
return -1;
}
if(end<=begin) {
return -1;
}
if(find>arr[mid]) {
begin = mid+1;
return BinarySearch(arr, find, begin, end);
}
if(find < arr[mid]) {
end = mid-1;
return BinarySearch(arr, find, begin, end);
}
return mid;
}
}