设计算法找出整数数组a[n](n<=50)中相差最小的两个元素(称为最接近数)的差。
输入格式:
第一行为数组大小n,第二行为n个数组元素,元素之间用空格分开
输出格式:
最接近数的差
输入样例:
5
65 38 26 75 40
输出样例:
2
代码位置:
package com.niuke.ALG;
import java.util.Scanner;
//最接近数
public class cloNumber {
//找最小数
public static int minNumber(int temp[]) {
int min=temp[1]-temp[0];
for(int i=2;i<temp.length;i++) {
if(min>temp[i]-temp[i-1]) {
min=temp[i]-temp[i-1];
}
}
return min;
}
// 冒泡排序法
public static int[] bubbleSort(int[]temp) {
for(int i=0;i<temp.length;i++) {
for(int j=0;j<temp.length-1-i;j++) {
if(temp[j]>temp[j+1]) {
int t =temp[j];
temp[j]=temp[j+1];
temp[j+1]=t;
}
}
}
return temp;
}
public static void main(String[] args) {
Scanner scan =new Scanner(System.in);
int n =scan.nextInt();
int a[]=new int[n];
for(int i=0;i<a.length;i++) {
a[i]=scan.nextInt();
}
a=bubbleSort(a);
System.out.println(minNumber(a));
}
}
运行截图位置: