我写出来一个比std::sort快的快排!!
查看原帖
我写出来一个比std::sort快的快排!!
1074084
asd890123楼主2024/5/13 19:02

void insert_sort(int v[],int l,int r){

int i,j,temp;

for (i = l;i <= r;i++){
    
	temp = v[i];
	for (j = i - 1;j >= l && temp < v[j];j--) v[j + 1] = v[j];
	v[j + 1] = temp;
	
}

}

void quik_sort(int v[],int l,int r){

std::stack <std::pair <int,int> > s;

s.push({l,r});
while (!s.empty()){
    
    int L = s.top().first,R = s.top().second;
    int i = L,j = R,flag = v[rand() % (R - L + 1) + L];
    
    s.pop();
    if (R - L <= 16){
        
        insert_sort(v,L,R);
        continue;
        
    }
    do{
        
        while (v[i] < flag) i++;
        while (v[j] > flag) j--;
        if (i <= j)
            std::swap(v[i],v[j]),i++,j--;
        
    }while (i <= j);
    if (L < j) s.push({L,j});
    if (i < R) s.push({i,R});
    
}

}

原先我的代一直比std::sort慢个10毫秒左右,现在
还能快个1ms!!!并且通过下一题测试也发现速度更
快(那题都用scanf读入,我的最长868ms,
std::sort最快870ms),(本题都使用fread版本快
读,我的16ms,std::sort17ms)
2024/5/13 19:02
加载中...