JAVA中的sort排序
来源:互联网 发布:不亦说乎的乐的读音 编辑:程序博客网 时间:2024/04/30 17:56
C++中提供了sort函数,可以让程序员轻松地调用排序算法,JAVA中也有相应的函数。
1.基本元素排序:Array.sort(排序数组名)
package test;import java.util.*;public class main{public static void main(String args[]){Scanner cin=new Scanner(System.in);int a[];int i;a=new int[5];for (i=0;i<=4;i++){a[i]=cin.nextInt();}Arrays.sort(a);for (i=0;i<=4;i++){System.out.println(a[i]+" ");}}}
2.基本元素从大到小排序:
由于要用到sort中的第二个参数,这个参数是一个类,所以应该用Integer,而不是int。可以使用Interger.intvalue()获得其中int的值
下面a是int型数组,b是Interger型的数组,a拷贝到b中,方便从大到小排序。capare中返回值是1表示需要交换。
package test;import java.util.*;class Mycomparator implements Comparator<Integer>{public int compare(Integer a,Integer b){if (a>b){return -1;}else if (a<b){return 1;}return 0;}}public class main{public static void main(String args[]){Scanner cin=new Scanner(System.in);int a[];Integer b[];int i;a=new int[5];b=new Integer[5];for (i=0;i<=4;i++){a[i]=cin.nextInt();b[i]=new Integer(a[i]);}Comparator<Integer> cmp=new Mycomparator();Arrays.sort(b,cmp);for (i=0;i<=4;i++){System.out.println(b[i].intValue()+" ");}}}
3.类排序。
和2差不多,都是重载比较器,以下程序实现了点的排序,其中x小的拍前面,x一样时y小的排前面
package test;import java.util.*;class point {int x,y;public String toString(){return "x="+x+" "+"y="+y;}}class pointComparator implements Comparator<point>{public int compare(point a,point b){if (a.x>b.x){return 1;}else if (a.x<b.x){return -1;}else{if (a.y>b.y){return 1;}else if (a.y<b.y){return -1;}}return 0;}}public class main{public static void main (String[] args){Scanner cin=new Scanner(System.in);int i,b;point a[]=new point[5];for (i=0;i<=4;i++){a[i]=new point();a[i].x=cin.nextInt();a[i].y=cin.nextInt();}Comparator<point> cmp=new pointComparator();Arrays.sort(a,cmp);for (i=0;i<=4;i++){System.out.println(a[i]);}}}
4.区间排序
如果只希望对数组中的一个区间进行排序,那么就用到sort中的第二个和第三个参数sort(a,p1,p2,cmp),表示对a数组的[p1,p2)(注意左闭右开)部分按cmp规则进行排序
0 0
- JAVA中的sort排序
- java中的Collections.sort排序
- java中的Collections.sort()排序详解
- 【算法】Java中的常见排序Sort
- java中的排序sort()函数的使用
- java List 排序 Collections.sort() 对 List 中的对象排序
- STL中的sort排序
- C#中的 sort排序
- lua中的sort排序
- Linux中的sort排序
- JavaScript中的sort排序
- Java中的自定义类型的排序(Comaprator, Collections.sort())
- java 中的 collections.sort() 方法对list的排序
- JAVA 中 Arrays.sort 中的排序的方法
- Collection(Collections.sort)中的Values排序问题-java
- Java中的经典算法之冒泡排序(Bubble Sort)
- Java中的经典算法之冒泡排序(Bubble Sort)
- 用Java集合中的Collections.sort方法对list排序
- 9.单字段分组和多字段分组
- 父类与子类
- Android模仿IOS的自定义switch
- BZOJ 1208 平衡树Treap模版题
- Java并发编程--CountDownLatch配合线程池
- JAVA中的sort排序
- Git 使用
- Mysql5-7-11 安装教程
- code
- LightOJ - 1241 Pinocchio (模拟)
- 前端学习总结(十六)前端工具之bower,glup,less总结
- 小白笔记----------------对象equals方法的使用
- 安卓手机机短信如何导入苹果IOS9以上版本
- 云计算时代商业银行的战略机会