码迷,mamicode.com
首页 > 编程语言 > 详细

数组中两个元素差的绝对值最小

时间:2016-01-07 08:53:08      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <stdlib.h>

/*
	给定一个含有n个元素的整型数组,
	找出数组中的两个元素x和y使得abs(x - y)值最小
*/

/*
	思路:
	排序,
	然后遍历数组比较相邻值相减得到的值
*/
typedef struct{
	int num1;
	int num2;
}TwoNumber;

TwoNumber getTNumber(int* numbers, int length);
int cmp(const void *a,const void *b);
int abs(int number);

int main(){
	int n;
	while (printf("Please input n:\n"), fflush(stdin), scanf("%d", &n) != EOF){
		if (n < 2){
			printf("Please input a bigger number.\n");
			continue;
		}
		int *numbers = (int*)malloc(n*sizeof(int));
		printf("Please input %d numbers: \n",n);
		for (int i = 0; i < n; ++i)
			scanf("%d", numbers + i);
		TwoNumber tNumber = getTNumber(numbers,n);
		printf("%d %d\n",tNumber.num1,tNumber.num2);
	}
	system("pause");
	return 0;
}

TwoNumber getTNumber(int* numbers, int length){
	qsort(numbers,length,sizeof(int),cmp);
	int absMinus = abs(numbers[0] - numbers[1]);
	int index = 0;
	for (int i = 1; i < length - 1; ++i){
		if (absMinus > abs(numbers[i] - numbers[i + 1])){
			absMinus = abs(numbers[i] - numbers[i + 1]);
			index = i;
		}
	}
	TwoNumber tNumber;
	tNumber.num1 = numbers[index];
	tNumber.num2 = numbers[index + 1];
	return tNumber;
}

int cmp(const void *a, const void *b){
	return *(int*)a - *(int*)b;
}

int abs(int number){
	if (number > 0)
		return number;
	else
		return -number;
}

  

数组中两个元素差的绝对值最小

标签:

原文地址:http://www.cnblogs.com/mutaohengheng/p/5108044.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!