二分法 递归查找普通查找 冒泡排序

public class intSearch {
public static void sort(int []a) {
//java中数组有length属性可以直接用

	  int temp;
	  for(int i=0;i<a.length-1;i++) {
		  for(int j=0;j<a.length-1-i;j++) {
			  if (a[j]>a[j+1]) {
               temp=a[j];
               a[j]=a[j+1];
               a[j+1]=temp;
			  }
		  }
	  }
  }
  //折半查找的前提是数组元素必须是有序的
  //非递归方法如下
  public static int erfenrearch(int[]a,int x) {
	  //使用递归和非递归两种方式查找一个整数
	  int f=0;//指向头
	  int r=a.length-1;//(#`O′)
	  while(f<=r)//头指针在尾指针的前边
	  {
		  int m=(f+r)/2;
		  //定义一个中间的指针
		  if (a[m]==x)return m;//返回位置
		  else if(a[m]>x) r=m-1;
		  else if(a[m]<x) f=m+1;
	  }
	  return -1;//如果头指针比尾指针大说明没有查找到元素的值
	  //停止查找返回负数
	  
  }
  //递归方法
  public static int hh(int []a,int f,int r,int x) {

	  int m=(f+r)/2;
	  if (f>r)return -1;
	  else {
		  if (x>a[m])//如果此处小于n往后找 
		  {
			return hh(a,m+1,r,x);  
		  }
		  else if(x<a[m]) {
			  return hh(a,f,m-1,x);
		  }
		  else //这是相等的情况
		  {return m;}
	  }
  }

}

Main:
import java.util.Scanner;
public class Main {

public static void main(String[] args) {
	// TODO Auto-generated method stub
      Scanner scan=new Scanner(System.in);
      int n=scan.nextInt();
      int[] a=new int[n];
      for(int i=0;i<n;i++) {
    	  a[i]=scan.nextInt();
      }
      scan.close();
      intSearch.sort(a);
      
      for(int i=0;i<a.length;i++) {
    	  System.out.println(a[i]);
      }//测试输出成功
      int m= intSearch.erfenrearch(a, 5);
      int x=intSearch.hh(a, 0, a.length-1,5);
      System.out.print(m+1);
      System.out.print(x+1);
}

}

猜你喜欢

转载自blog.csdn.net/qingyibaicai/article/details/83279571
今日推荐