最简单易懂的java数组排序方法整理
作者:关键我是你杰哥 时间:2023-01-03 18:56:41
前言
JAVA中在运用数组进行排序功能时,一般有四种方法:快速排序法、冒泡法、选择排序法、插入排序法。本文就给大家介绍了关于最简单易懂的java数组排序方法,下面话不多说了,来一起看看详细的介绍吧
方法如下:
1、快速排序:首先是最简单的Array.sort,直接进行排序:
public static void main(String[] args) {
int[] arr = {4,3,5,1,7,9,3};
Arrays.sort(arr);
for (int i : arr){
System.out.println(i);
}
点击运行即可输出已排序的数组数字。
2、部分排序法:使用Array.sort还可进行选择想要排序的部分数字,如将下角标编号为1~4的数字进行排序,其他数字顺序不变。
public static void main(String[] args) {
int[] arr = {4,3,5,1,2,9,3,0};
Arrays.sort(arr,1,4);
for (int i = 0;i<arr.length;i++){
System.out.print(arr[i]+",");
}
}
输出结果为:4,1,3,5,2,9,3,0, 可见仅下标为1~4的数字进行了排序。
3、冒泡排序法:顾名思义,从下到上,两两进行比较,越小的越往上,从而形成由小到大的排序。
public static void bubble(int[] arr){
int temp;
//根据角标进行比较,
for(int i = 0; i<arr.length; i++){
//j是数组的最后一个角标
for (int j = arr.length-1; j > i; j--) {
if (arr[j] < arr[j - 1]) {
//从后往前进行比较,小数往前,一轮之后最小数就在最前面了
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {3,22,5,3,66,2,9};
bubble(arr);
//使用foreach循环输出
for(int x : arr){
System.out.println(x);
}
//使用字符串表达形式输出,输出形式更为直观
System.out.println(Arrays.toString(arr));
}
来源:https://www.cnblogs.com/yjboke/p/8488144.html
标签:java,数组,排序
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
解决Java中的java.io.IOException: Broken pipe问题
2022-01-24 00:40:34
![](https://img.aspxhome.com/file/2023/4/94384_0s.png)
高吞吐、线程安全的LRU缓存详解
2021-10-01 01:40:28
![](https://img.aspxhome.com/file/2023/1/104201_0s.png)
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
2021-06-01 14:28:00
![](https://img.aspxhome.com/file/2023/3/66253_0s.jpg)
C#编程中常见数据结构的比较(Unity3D游戏开发)
2022-01-02 06:58:03
Java安全 ysoserial CommonsCollections3示例分析
2022-01-19 05:08:19
![](https://img.aspxhome.com/file/2023/3/124713_0s.png)
Java BoxLayout(盒子布局)布局管理器解析
2022-07-19 05:26:09
![](https://img.aspxhome.com/file/2023/3/63783_0s.png)
解析Java中PriorityQueue优先级队列结构的源码及用法
2023-11-08 13:33:11
![](https://img.aspxhome.com/file/2023/5/91065_0s.png)
c# Struct的一些问题分析
2023-08-31 08:27:36
详解Spring Boot读取配置文件与配置文件优先级
2022-03-23 13:14:23
Android 将文件下载到指定目录的实现代码
2021-06-11 04:44:41
一个简陋的java图书管理系统
2021-08-10 23:49:40
Springboot如何获取yml、properties参数
2021-09-20 17:34:43
![](https://img.aspxhome.com/file/2023/3/129233_0s.jpg)
Android 中Banner的使用详解
2023-08-18 08:57:02
Java编程用指定字符打印菱形实例
2022-02-23 05:49:09
C#中添加窗口的步骤详解
2021-12-19 16:30:29
![](https://img.aspxhome.com/file/2023/6/91256_0s.jpg)
C# WinForm状态栏实时显示当前时间(窗体状态栏StatusStrip示例)
2022-10-09 16:58:51
![](https://img.aspxhome.com/file/2023/6/111166_0s.png)
详解Android XML中引用自定义内部类view的四个why
2023-06-01 19:40:41
Android控件View打造完美的自定义侧滑菜单
2021-06-16 07:44:00
![](https://img.aspxhome.com/file/2023/1/137741_0s.gif)
Java多线程通信wait()和notify()代码实例
2022-09-27 12:12:11
Android Shape属性创建环形进度条
2021-08-02 09:03:08
![](https://img.aspxhome.com/file/2023/4/94274_0s.gif)