【转载合集】排序算法工具箱

// 二分查找改进的插入排序
void insertionSortBSearch(int a[], n) {
for (int i = 1; i < n; ++i) {
int j, val = a[i];
int begin = 0, end = i - 1;
while (begin < end) {
int mid = begin + (end - begin) / 2;
if (a[mid] > val) {
end = mid - 1;
}
else {
begin = mid;
}
}
for (j = i - 1; j >= begin; --j) {
a[j + 1] = a[j];
}
a[begin] = val;
}
}

   

来自 <https://www.jianshu.com/p/916b15eae350>

   

class A {

public:

int a1, a2;

A(int m, int n): a1(m), a2(n) {}

};

   

class B {

public:

int b1, b2;

B(int m, int n): b1(m), b2(n) {}

};

   

bool cmp1(A const *a, A const *b) {

return a->a1 < b->a1;

}

   

bool cmp2(B const &a, B const &b) {

return a.b1 < b.b1;

}

   

int main() {

vector<A*> array;

sort(array.begin(), array.end(), cmp1);

sort(array2.begin(), array2.end(), cmp2);

return 0;

}

/* Input matrix
m = [
1 4 2
0 8 3
3 5 1
]
*/

// Ascending order by first column
sort(m.begin(), m.end());
/*
m = [
0 8 3
1 4 2
3 5 1
]
*/

// Descending order by first column
sort(m.rbegin(), m.rend());
/*
m = [
3 5 1
1 4 2
0 8 3
]
*/

// Ascending order by second column
sort(m.begin(), m.end(), [](const vector<int> &a, const vector<int> &b) { return a[1] < b[1]; } );

bool cmp(const vector<int> &a, const vector<int> &b) {
return
a[0] > b[0];
}
sort(m.begin(), m.end(), cmp);
/*
m = [
1 4 2
3 5 1
0 8 3
]
*/

// Descending order by second column
sort(m.begin(), m.end(), [](const vector<int> &a, const vector<int> &b) { return a[1] > b[1]; } );

bool cmp(const vector<int> &a, const vector<int> &b) {
return
a[0] < b[0];
}
sort(m.begin(), m.end(), cmp);
/*
m = [
0 8 3
3 5 1
1 4 2
]
*/

   

来自 <https://www.cnblogs.com/grandyang/p/4843528.html>

posted @ 2019-12-16 09:00  拓海藤原  阅读(138)  评论(0编辑  收藏  举报