算法,感觉思维模型比较重要
对比std::sort。。。的比较输出, 发现std::sort 底层并不是或不完全是快排实现
#include <stdio.h>
#include <algorithm>
//前闭,后开
void quicksort(int start, int end, int* a){
if (start+1 >= end) { //只有一个数据或数据单方向偏
return;
}
//printf("start:%d, end:%d\n", start, end);
int temp = a[start];
int low = start;
int high = end-1;
while(low<high){
printf("k:%d, k:%d\n", temp, a[high]);
//if(temp>a[high]){
if(temp<a[high]){
a[low++] = a[high];
while(low<high){
printf("k:%d, k:%d\n", temp, a[low]);
//if(temp<a[low]){
if(temp>a[low]){
a[high--] = a[low];
break;
}else{
++low;
}
}
}else{
--high;
}
}
a[low] = temp;
quicksort(start, low, a);
quicksort(low+1, end, a);
}
void print(int a){
printf("%d ", a);
}
int main(){
int a[] = {3 ,4 ,2 , 6, 6};
quicksort(0, sizeof(a)/sizeof(int), a);
std::for_each(a, a+sizeof(a)/sizeof(int), print);
puts("");
return 0;
}
---------------------------------------------------
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
struct Node{
int age;
int id;
bool operator<(const Node& e) const{
return (this->id<e.id);
}
};
bool comp(Node e1, Node e2){
printf("%d %d\n", e1.id, e2.id);
return (e1.id > e2.id);
}
/*
int compar(const void* node1, const void * node2){
Node& e1 = *(Node*)node1;
Node& e2 = *(Node*)node2;
if(e1.id>e2.id){
return 1;
}else if(e1.id<e2.id){
return -1;
}
return 0;
}*/
int main(){
Node nodes[] = { {10,3}, {11,4}, {19,2}, {25,6}, {45, 6} };
int cnt = sizeof(nodes)/sizeof(Node);
printf("cnt:%d\n", cnt);
//qsort(nodes, cnt, sizeof(Node), compar); //稳定排序
std::sort(nodes, nodes+cnt, comp);
//std::sort(nodes, nodes+cnt);
for(int i=0; i<cnt; ++i){
printf(" node=age:%d,id:%d ", nodes[i].age, nodes[i].id);
}
puts("");
return 0;
}