java中sort函数的使用
写在前面
想必大家都知道C++里面的sort用过的都知道这个函数是绝对好用,不开玩笑,什么冒泡,快排,二分啊,讲真的还是sort是真的香。但是java里面也有sort函数只不过使用方式有些不同而已,下面就是我整理的一些笔记啦,可以帮你快速搞定sort,一文在手,sort无忧。
sort函数的基本格式
导入:import java.util.Arrays;
第一种基本格式
Array.sort(数组名,起始下标,终止下标)
默认为升序
下面看使用范例:
import java.util.Arrays;
public class test {
public static void main(String args[]) {
int[] a ={1,8,6,9,4,7,6};
Arrays.sort(a,0,a.length);
for(int i : a){
System.out.print(i+" ");
}
}
}
输出结果:
第二种基本格式
Arrays.sort(数组名)
默认升序,这种情况只适合数组已被初始化
使用范例
import java.util.Arrays;
public class test {
public static void main(String args[]) {
int[] a ={1,8,6,9,4,7,6};
Arrays.sort(a);
for(int i : a){
System.out.print(i+" ");
}
}
}
第三种基本格式cmp
函数的基本格式
int compare (Object o1,Object o2);
传入参数的类型是java中的类
这时的sort函数的格式变成了:
Arrays.sort(数组名,起始下标,终止下标,new cmp());
返回值的基本方法:
int compare(Object o1, Object o2) 返回一个基本类型的整型 如果要按照升序排序, 则o1 小于o2,返回-1(负数),相等返回0,01大于02返回1(正数) 如果要按照降序排序 则o1 小于o2,返回1(正数),相等返回0,01大于02返回-1(负数)
测试样例代码
package qiuqiu;
import java.util.*;
import java.util.Arrays;
class node{
int x;
}
class cmp implements Comparator<node>{
public int compare(node a,node b){
if(a.x<b.x)
return 1;
else if(a.x>b.x)
return -1;
else
return 0;
}
}
public class yun{
public static void main(String args[]){
node[] a = new node[10];
Scanner cin = new Scanner(System.in);
System.out.println("请输入10个整数:");
int t=10,i=0;
while(t>0){
a[i] = new node(); // 这里不要漏掉,第19行只是创建10个node对象,这里才是创建具体的空间
a[i].x=cin.nextInt();
i++;
t--;
}
Arrays.sort(a,0,a.length,new cmp());
System.out.println("从小到大排序结果后:");
for (node k :a){
System.out.print(k.x+" ");
}
System.out.print("\n");
}
}
输出: