Custom rule sort sorting

Custom sort of java:

1. Sorting wrapper class object must not be the basic data types;

2. Call Arrays.sort (array, left, right, cmp) to sort, array to array, left, right in the range, cmp is a comparison function that you define;

3. cmp defined objects need to rewrite Comparator <> compare methods of the class;

import java.util.*;
public class Main
{
	static Integer []A = null;
	public static void main(String args[]) 
	{
		Scanner in = new Scanner(System.in);
		Comparator<Integer> cmp = new Comparator<Integer>() {
			public int compare(Integer a, Integer b) {
				return b - a;//降序
			}
		};
		int n = in.nextInt();
		A = new Integer [n];
		for (int i = 0; i < n; i++) A[i] = in.nextInt();
		Arrays.sort(A, 0, n, cmp);
		for (Integer i : A) System.out.println(i);
	}

Review the custom sort c ++

The first: custom class

The comparison function to compare sort of declared as static member function or global function , not as an ordinary member function, otherwise it will error. invalid use of non-static member function
as: non-static member function is dependent on the specific object, and std :: sort these functions are global, and therefore can no longer sort of call non-static member function.

Static member functions or global functions are not dependent on a specific object, you can access independently, without having to create any object instance can access. Meanwhile static member function can not call non-static member class. 

#include <iostream>
#include "algorithm" 
#include "cmath"
using namespace std;
class deal{
	public: 
	static bool cmp(int l,int r){
		return l>r;//降序 
	}
	void test(int *arr,int size){
	sort(arr,arr+size,cmp);
	for(int i=0;i<size;++i)
	cout<<arr[i]<<" ";
	cout<<'\n';	
	}
};	
int main()
{
	deal a;
	int arr[8]={1,9,2,3,7,0,6,4};
	a.test(arr,8);
    return 0;
}  

The second custom comparison function:

#include <iostream>
#include "algorithm" 
#include "cmath"
using namespace std;
bool cmp(int l,int r){
	return l>r;
}
int main()
{
	
	int arr[8]={1,9,2,3,7,0,6,4};
	sort(arr,arr+8,cmp);
	for(int i=0;i<8;i++)
	cout<<arr[i]<<' ';
	cout<<endl;
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/cstdio1/p/11228034.html