Before the callback function is not very understanding, after colleagues reminded, suddenly dawned.
Today we start with the bubble sort, bubble sort everyone should know that all of the programming languages that have been exposed, the first sort you know, should be it.
Bubble sort
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;
}
}
}
}
When we need to implement a sort order that is determined by the caller, the bubbling sort becomes the underlying code and cannot be tampered with, when the callback function comes in handy.
Defining interfaces
Interface comparator{
int compare (int a,int b);
}
Implementation class
Returns 0 if A>b returns 1;A<B 1;
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;
}
}
}
Reverse order
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;
}
}
}
Requires a comparator interface
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;
}
}
}
}
Main program
public static void Main (string[] args) {
Int[] Array=new int[]{11,22,33,44,11};
Descending arrangement
Passing a class that implements interface comparator
Sort (array,new mycomparatordesc ());
for (int arr:array)
{
System.out.print (arr+ "");
}
Ascending order
Sort (array,new mycomparator ());
for (int arr:array)
{
System.out.print (arr+ "");
}
This article is from the "about to buy wine bottle" blog, please be sure to keep this source http://22228888.blog.51cto.com/8047750/1587670
Java callback function rollback