数组中的最小差异

编程入门 行业动态 更新时间:2024-10-10 08:23:15
本文介绍了数组中的最小差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想要找到一个数组的所有元素之间的最小差异。我阅读了各种其他问题,但无法找到错误的确切来源在以下代码。

I want to find the minimum difference among all elements of an array. I read through various other questions, but couldn't find the exact source of the error in the following code.

#include<iostream> #include<stdio.h> #include<cstdlib> using namespace std; void quicksort(long int *lp, long int *rp); int main() { int t,n; long int s[5000]; cin>>t; while(t--){ cin>>n; for(int i=0;i<n;i++) cin>>s[i]; quicksort(&s[0],&s[n-1]); //cout<<"passes:"<<passes<<endl; //for(int i=0;i<n;i++) cout<<s[i]<<" "; long int min = abs(s[1]-s[0]); //cout<<endl<<min; for(int i=1;i<(n-1);i++){ long int temp = abs(s[i]-s[i+1]); if (temp <= min) min = temp; } cout<<min; } } void quicksort(long int *lp,long int *rp){ int arraysize= (rp-lp)+1; if(arraysize > 1){ long int *pivot = (lp+(arraysize/2)); long int swap=0; long int *orgl = lp; long int *orgr = rp; while(lp!=rp){ while (*lp < *pivot) lp++; while (*rp > *pivot) rp--; if (lp == pivot) pivot=rp; else if (rp == pivot) pivot=lp; swap = *lp; *lp = *rp; *rp = swap; if((*lp == *pivot) || ( *rp == *pivot)) break; } quicksort(orgl,pivot-1); quicksort(pivot+1,orgr); }

}

问题陈述在此链接中提供: www.codechef/problems/HORSES 你能确定我的程序中的错误吗?

The problem statement is given in this link : www.codechef/problems/HORSES Can you please identify the error in my program ?

推荐答案

快速排序这不是真正保证O(n * logn)你最好使用排序从< algorithm> 。 这个逻辑看起来不错:

You are using C++ so instead of using your custom quicksort which is not really guarantee O(n*logn) you better use sort from <algorithm>. This logic looks good:

long int min = abs(s[1]-s[0]); //cout<<endl<<min; for(int i=1;i<(n-1);i++){ long int temp = abs(s[i]-s[i+1]); if (temp <= min) min = temp; } By the way: cout<<min; Add cout<<min << endl;

更多推荐

数组中的最小差异

本文发布于:2023-11-29 06:20:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645589.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   最小   差异

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!