我是靠谱客的博主 甜甜外套,最近开发中收集的这篇文章主要介绍Java第三大的数,Java通过排序找出数组第三大数字,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Java通过排序找出数组第三大数字

1 方式一:对数组进行排序并返回第三大数字

通过对数组进行排序并返回第三大数字,我们可以找到java中的第三大数字。让我们看看完整的示例,以找到java数组中的第三大数字。

/**

* 一点教程网: http://www.yiidian.com

*/

public class ThirdLargestInArrayExample{

public static int getThirdLargest(int[] a, int total){

int temp;

for (int i = 0; i < total; i++)

{

for (int j = i + 1; j < total; j++)

{

if (a[i] > a[j])

{

temp = a[i];

a[i] = a[j];

a[j] = temp;

}

}

}

return a[total-3];

}

public static void main(String args[]){

int a[]={1,2,5,6,3,2};

int b[]={44,66,99,77,33,22,55};

System.out.println("Third Largest: "+getThirdLargest(a,6));

System.out.println("Third Largest: "+getThirdLargest(b,7));

}

}

以上代码输出结果为:

Third Largest:3

Third Largest:66

2 方式二:使用Arrays类找出数组的第三大数字

让我们看看另一个示例,该示例使用Arrays在Java数组中获取第三大元素的数字。

/**

* 一点教程网: http://www.yiidian.com

*/

import java.util.*;

public class ThirdLargestInArrayExample1{

public static int getThirdLargest(int[] a, int total){

Arrays.sort(a);

return a[total-3];

}

public static void main(String args[]){

int a[]={1,2,5,6,3,2};

int b[]={44,66,99,77,33,22,55};

System.out.println("Third Largest: "+getThirdLargest(a,6));

System.out.println("Third Largest: "+getThirdLargest(b,7));

}}

以上代码输出结果为:

Third Largest: 3

Third Largest: 66

3 方式三:使用Collections获取数组的第三大数字

/**

* 一点教程网: http://www.yiidian.com

*/

import java.util.*;

public class ThirdLargestInArrayExample2{

public static int getThirdLargest(Integer[] a, int total){

List list=Arrays.asList(a);

Collections.sort(list);

int element=list.get(total-3);

return element;

}

public static void main(String args[]){

Integer a[]={1,2,5,6,3,2};

Integer b[]={44,66,99,77,33,22,55};

System.out.println("Third Largest: "+getThirdLargest(a,6));

System.out.println("Third Largest: "+getThirdLargest(b,7));

}}

以上代码输出结果为:

Third Largest: 3

Third Largest: 66

最后

以上就是甜甜外套为你收集整理的Java第三大的数,Java通过排序找出数组第三大数字的全部内容,希望文章能够帮你解决Java第三大的数,Java通过排序找出数组第三大数字所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(34)

评论列表共有 0 条评论

立即
投稿
返回
顶部