OJ常用技巧-排序
1. C/C++
#include
#include
int compare_ints(const void* a, const void* b) {
int arg1 = *(const int*)a;
int arg2 = *(const int*)b;
if (arg1 < arg2) return -1;
if (arg1 > arg2) return 1;
return 0;
}
int main(void) {
int ints[] = { -2, 99, 0, -743, 2, INT_MIN, 4 };
int size = sizeof ints / sizeof *ints;
qsort(ints, size, sizeof(int), compare_ints);
}
#include
#include
#include
int main() {
std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
std::sort(s.begin(), s.end());
std::sort(s.begin(), s.end(), std::greater<int>());
struct {
bool operator()(int a, int b)
{
return a < b;
}
} customLess;
std::sort(s.begin(), s.end(), customLess);
std::sort(s.begin(), s.end(), [](int a, int b) {
return b < a;
});
}
2. Java
import java.util.Comparator;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
List s =
new ArrayList(Arrays.asList(5, 7, 4, 2, 8, 6, 1, 9, 0, 3));
Collections.sort(s);
Collections.sort(s, new Comparator() {
@Override
public int compare(Integer a, Integer b) {
return a.compareTo(b);
}
}.reversed());
s.sort(Integer::compareTo);
s.sort((a, b) -> b.compareTo(a));
for (int n : s) { System.out.print(n+", "); } System.out.println();
}
}
3. Python
data = [('a', 5), ('c', 7), ('b', 4), ('g', 2), ('h', 8),
('e', 6), ('i', 1), ('f', 9), ('j', 0), ('d', 3)]
data.sort()
data.sort(reverse=True)
data.sort(cmp=lambda x, y: x[1] - y[1])
data.sort(cmp=lambda x, y: x[1] - y[1], reverse=True)