相信很多同学在刷算法题的时候,都会遇到需要自定义排序数组的场景,这里做一个总结,后端常见语言的自定义排序方法,包括Golang,Java,C/C++,Python。
这里先统一一下场景,场景是一个商品数组,有两个属性,分别是价格和和评分,优先按价格从低到高排,如果价格一样,按照评分从高到低排。
Golang
package codes
import (
"sort"
)
type Product struct {
Price float64
Score int
}
func Sort(arr []Product) {
// 自定义排序
sort.Slice(arr, func(i, j int) bool {
if arr[i].Price != arr[j].Price {
return arr[i].Price < arr[j].Price
}
return arr[i].Score > arr[j].Score
})
}
在golang语言中,自定义排序可以使用sort包的slice方法,传入的第一个参数为切片类型的待排序数组,第二个参数为less函数,该函数的两个参数i和j分别表示待排序数组中的两个下标,less函数定义这两个下标对应的项的大小如何比较,即什么时候i对应的项要排在j对应的项的前面。
C
#include <stdio.h>
#include <stdlib.h>
typedef struct {
double price;
int score;
} Product;
int compare_product(const void *a, const void *b) {
const Product *p1 = (const Product *)a;
const Product *p2 = (const Product *)b;
if (p1 -> price != p2 -> price) {
return p1 -> price - p2 -> price;
}
return p2 -> score - p1 -> score;
}
int main() {
Product product[] = {{19, 20}, {10, 11}, {19, 29}, {19, 11}, {23, 0}};
int n = sizeof(product) / sizeof(product[0]);
// 使用qsort进行排序
qsort(product, n, sizeof(Product), compare_product);
// 打印排序后的结果
for (int i = 0; i < n; i++) {
printf("{Price: %f Score: %d}", product[i].price, product[i].score);
if (i != n - 1) {
printf(" ");
} else {
printf("\n");
}
}
return 0;
}
可以使用c标准库中的qsort函数,一共四个参数,最后一个参数为比较函数,传入的是两个指向两个项的指针,返回值为int,可以这样理解:返回值为负数的情况下表示第一个参数对应的项要排在第二个参数对应的项的前面。
c++
#include<iostream>
#include<vector>
#include<algorithm>
class Product {
public:
double price;
int score;
};
bool compareItems(const Product& p1, const Product& p2) {
if (p1.price != p2.price) {
return p1.price < p2.price;
}
return p1.score > p2.score;
}
int main() {
std::vector<Product> product = {{19, 20}, {10, 11}, {19, 29}, {19, 11}, {23, 0}};
std::sort(product.begin(), product.end(), compareItems);
for (const auto& p : product) {
std::cout << "{Price: " << p.price << ", " << "Score: " << p.score << "} ";
}
return 0;
}
c++ 自定义排序可以使用stl库中的sort函数,传入的比较函数的逻辑和golang语言的类似。
java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Product {
double price;
int score;
public Product(double price, int score) {
this.price = price;
this.score = score;
}
public static void main(String[] args) {
List<Product> products = new ArrayList<>();
products.add(new Product(19, 20));
products.add(new Product(10, 11));
products.add(new Product(19, 29));
products.add(new Product(19, 11));
products.add(new Product(23, 0));
// 自定义排序
Collections.sort(products, new Comparator<Product>() {
@Override
public int compare(Product p1, Product p2) {
if (p1.price != p2.price) {
return (int)(p1.price - p2.price);
}
return p2.score - p1.score;
}
});
// 输出排序结果
for (Product product: products) {
System.out.printf("{Price: %f; Score: %d}", product.price, product.score);
}
}
}
java语言的自定义排序和c语言中的qsort传入的比较函数有点类似。
python
class Product:
price: float
score: int
def __init__(self, price, score):
self.price = price
self.score = score
def sort_product(products: list[Product]) -> list[Product]:
sorted_products = sorted(products, key=lambda product: (product.price, -product.score))
return sorted_products
if __name__ == "__main__":
products = [Product(19, 20), Product(10, 11), Product(19, 29), Product(19, 11), Product(23, 0)]
sorted_products = sort_product(products)
for product in sorted_products:
print("{Price: %f; Score: %d}", product.price, product.score)
python自定义排序可以使用内建函数sorted, 传入key可以用lambda表达式,多个key用括号,倒排就用字段的负数。
1873






