之前对回调函数不是很理解,经同事提醒,恍然大悟.

        今天我们就从冒泡排序开始说起,冒泡排序大家应该都知道,所有接触过编程语言的,所知道的第一个排序应该都是它.

    //冒泡排序

private static void sort(int[] a,Comparator comparator)
 {
      for(int i=0;i<a.length;i++)
      {
               for(int j=0;j<a.length-i-1;j++)
           {
                if(comparator.compare(a[j],a[j+1])==1)
                {
                     int     temp=a[j];
                     a[j]    =    a[j+1];
                     a[j+1] =    temp;
                } 
            }
      } 
 }

当我们需要实现 排序顺序 由调用者决定时,冒泡排序就变成了底层代码,不能乱动,这时回调函数就派上用场了

定义接口

interface Comparator{
 int compare(int a,int b);
  
}

实现类

//如果a>b返回1;a<b返回-1;否则返回0
class MyComparator implements Comparator{

 public int compare(int a, int b) {
       if(a > b){
         return 1;
  } else if(a < b){
   return -1;
  } else {
   return 0;
  }
 }
}

 

//倒序排列
class MyComparatorDesc implements Comparator{
 public int compare(int a, int b) {
  if(a > b){
   return -1;
  } else if(a < b){
   return 1;
  } else {
   return 0;
  }
 }
 
}

 //需要一个comparator接口

private static void sort(int[] a,Comparator comparator)
 {
  for(int i=0;i<a.length;i++)
  {
   for(int j=0;j<a.length-i-1;j++)
   {
    if(comparator.compare(a[j],a[j+1])==1)
    {
     int temp=a[j];
     a[j]=a[j+1];
     a[j+1]=temp;
    }
   }
  } 
 } 

 

主程序

public static void main(String[] args) {
  int[] array=new int[]{11,22,33,44,11};
  //降序排列

//传递一个实现接口Comparator的类
  sort(array,new MyComparatorDesc());
  for(int arr:array)
  {
   System.out.print(arr+"  ");
  }
  //升序排列
  sort(array,new MyComparator());
  for(int arr:array)
  {
   System.out.print(arr+"  ");
  }