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");
    }
}

输出:
在这里插入图片描述

  • 13
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Liknana

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值