首页 > Java > java教程 > Java 中的排序

Java 中的排序

王林
发布: 2024-08-30 15:29:35
原创
486 人浏览过
  • Java 中的排序基本上就是按特定顺序排列存储在某处的一组元素;该顺序可以是升序或降序;在实时编程中,有很多场景需要对元素进行排序,因为这也使得搜索特定元素变得容易,因为如果排序,可以直接通过数组索引轻松检索元素。需要排序的元素可以存储在数组或集合中。集合有多种类型,如 Java 中的 Sets、Tree、Map、Heap、List 等,尽管有不同类型的排序算法用于对类似数组中的元素进行排序,如冒泡排序、堆排序、插入排序、选择排序、归并排序等
  • 程序员根据自己的具体要求和算法的复杂程度,使用不同的算法对元素进行排序。这些排序算法是通过使用各种循环和变量来迭代它们来实现的。除了使用排序算法对数组中的元素进行排序之外,Java 还提供了内置的排序功能,这可以帮助实现同样的目的,并且程序员不需要陷入大循环并考虑复杂性。是的,你没听错,在 Java 中,sort() 函数用于对存储在数组或集合中的元素进行排序,并且其复杂度非常低 o(n(logn))。然而,两者的方法实现有点不同。

数组语法:

Arrays.sort(array_name);
登录后复制

收藏

开始您的免费软件开发课程

网络开发、编程语言、软件测试及其他

Collections.sort(array_name_list);
登录后复制
  • 这里的array_name和array_name_list是需要排序的数组或集合的名称。
  • 数组是 Java 类的名称。
  • 集合是Java中的一个框架。
  • sort() 是 Java 中使用的内置排序函数。

Java 中排序是如何进行的?

以下几点:

  • 通过使用排序算法,还可以使用低效到高效的不同算法进行排序,每种算法都有自己的时间和空间复杂度。
  • 有时这些算法的复杂度非常高,无法在需要处理大量数据的实际场景中使用。
  • 如上所述,在Java内置函数中,sort()用于对数组和集合的所有元素进行排序。根据Java官方文档,Array.sort使用的是快速排序,即双主元快速排序,比单主元快速排序要快得多。
  • 这样做的最大优点之一是它提供了 O(n(logn)) 的复杂度。它使用归并排序数组对象的非常稳定和迭代的实现。 Java也提供了一种对数组进行逆序排序的方法,可以根据程序员的需求进行升序或降序排序。 Collections.reverseOrder() 方法用于对元素进行反向或降序排序。
  • Java 8 还提供了使用并行排序对数组进行并行排序的功能,它使用 Java 的多线程概念,将整个数组分成几部分,并在排序后合并它们。

Java 中的排序类型

下面提到了 Java 排序中执行排序的一些方法:

1.排序(数组名称)

这用于对整个数组进行升序排序。默认情况下,此方法按升序对数组元素进行排序。

代码:

import java.util.Arrays;
public class SimpleSort
{
public static void main(String[] args)
{
//Unsorted array of numbers
Integer[] arr = new Integer[] {100, 20, 10, 30, 80, 70, 90, 40, 50, 60};
//Sort function to sort the above array
Arrays.sort(arr);
//Printing the sorted array on console
System.out.println(Arrays.toString(arr));
}
}
登录后复制

输出:

Java 中的排序

2. Collection.reverseOrder()

Java中该方法用于对数组进行倒序或降序排序。有些场景我们需要对元素进行降序排序,Java 是通过内置方法来实现的。

代码:

import java.util.Arrays;
public class ReverseSort
{
public static void main(String[] args)
{
//Unsorted array of numbers
Integer[] arr = new Integer[] { 100, 20, 10, 30, 80, 70, 90, 40, 50, 60};
//Sort function to sort the above array
Arrays.sort(arr, Collections.reverseOrder());
//Printing the sorted array on console
System.out.println(Arrays.toString(arr));
}
}
登录后复制

输出:

Java 中的排序

3. sort(int[ ] array_name, int findex, int lindex)

如果需要对数组的某些部分而不是整个数组进行排序,Java 提供了通过指定 3 个参数来对此类数组进行排序的工具,即数组名称、需要开始排序的第一个索引以及最后一个索引,直到需要进行排序为止。

代码:

import java.util.Arrays;
public class ReverseSort
{
public static void main(String[] args)
{
//Unsorted array of numbers
Integer[] arr = new Integer[] { 100, 20, 10, 30, 80, 70, 90, 40, 50, 60};
//Sort function to sort the above array
Arrays.sort(arr, 1, 5);
//Printing the sorted array on console
System.out.println(Arrays.toString(arr));
}
}
登录后复制

输出:

Java 中的排序

4. Arrays.parllelSort(array_name)

From Java 8, the new API of the parallel sort has been released. Basically, in Parallel sort, the array is divided into 2 sub-arrays, and then the basic Array.sort() function is performed by a separate thread. The sorted arrays are then merged in the end to form the fully sorted array. This is done to leverage the use of multi-threading.

Code:

import java.util.Arrays;
public class ParallelSort
{
public static void main(String[] args)
{
//Unsorted array of numbers
Integer[] arr = new Integer[] { 100, 20, 10, 30, 80, 70, 90, 40, 50, 60};
//parallel Sort function to sort the above array
Arrays.parallelSort(arr);
//Printing the sorted array on console
System.out.println(Arrays.toString(arr));
}
}
登录后复制

Output:

Java 中的排序

Like a normal Array.sort(), Arrays.parallelSort() also provides the facility to sort a particular range of array or sorting an array in reverse order.

Syntax:

// to Sort a range of array by parallelsort
Arrays.parallelSort(array_name, findex, lindex);
// to sort an array in reverse order using parallelSort
Arrays.parallelSort(array_name, Collections.reverseOder());
登录后复制

5. Collection.sort()

This method is used to sort the collections like list, map, Set, etc. It uses the merge sort and gives the same complexity as Array.sort(), i.e. O(n(logn)).

1. Sorting a List in ascending order

Code:

import java.util.Arrays;
import java.util.Collections;
public class ListSort
{
public static void main(String[] args)
{
//Unsorted list
Integer[] arr = new Integer[] { 100, 20, 10, 30, 80, 70, 90, 40, 50, 60 };
List<Integer> arrList = Arrays.asList(arr);
//Sorting of list using the method
Collections.sort(arrList);
//Printing the list sorted above
System.out.println(arrList);
}
}
登录后复制

Output:

Java 中的排序

2. Sorting an Array List in descending order

Code:

import java.util.Arrays;
import java.util.Collections;
public class ListSortRev
{
public static void main(String[] args)
{
//Unsorted array list of Integers
Integer[] arr = new Integer[] {100, 20, 10, 30, 80, 70, 90, 40, 50, 60 };
List<Integer> arrList = Arrays.asList(arr);
//Sorting of list using the method
Collections.sort(arrList);
//Printing the list sorted above
System.out.println(arrList);
}
}
登录后复制

Output:

Java 中的排序

3. Sorting of Set

There are 3 basic rules while sorting a collection ‘Set’ using the above method sort(array_name):

    1. Convert the Set into the list.
    2. Sort the list using the method sort(array_name).
    3. Convert the resulting sorted List back to Set.

Code:

List<Integer> numList = new ArrayList<Integer>(num) ;
//Sorting the list retrieved above
Collections.sort(numList);
// Converting sorted List into Set
num = new LinkedHashSet<>(numList);
//Printing the Resulting Set on console
System.out.println(num);
}
}
登录后复制

Output:

Java 中的排序

4. Sort a Map

Collection Map in Java is a combination of key and value So sorting can be done both ways, either through key or by value.

  • Sort a Map by Key: Let’s see the below example of Sorting a Map by Key.

Code:

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class SortHashKey
{
public static void main(String[] args)
{
HashMap<Integer, String> map = new HashMap<>();
map.put(80, "Akshay");
map.put(20, "Akash");
map.put(10, "Bob");
map.put(30, "Nitika");
map.put(90, "Yashi");
map.put(100, "Dragisa");
TreeMap<Integer, String> treeMap = new TreeMap<>(map);
System.out.println(treeMap);
}
}
登录后复制

Output:

Java 中的排序

One of the easiest ways to sort the elements of the Map by Keys is by adding the unsorted map elements in the TreeMap. TreeMap automatically sorts the elements in the ascending order of Hash Keys. Though collection.sort() can also be used to do the same, it is somewhat complex and needs to be coded well.

  • Sort a Map by Value: Below mentioned is an example of how the sorting can be done in a Map using value.

Code: 

import java.util.HashMap;
import java.util.Map;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
public class SortHashValue
{
public static void main(String[] args)
{
HashMap<Integer, String> map = new HashMap<>(); map.put(80, "Akshay");
map.put(20, "Akash");
map.put(10, "Bob");
map.put(30, “Nitika");
map.put(90, "Yashi");
map.put(100, "Dragisa");
LinkedHashMap<Integer, String> sorted = new LinkedHashMap<>(); map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.forEachOrdered(x -> sorted.put(x.getKey(), x.getValue()));
登录后复制

Output:

Java 中的排序

In the above example of sorting of Map by value, firstly we set the entries using the map.entrySet() and then stream of those entries using stream() method, call the sorted array using sorted() method by comparing by value in the pair. for each ordered() is used to traverse the stream to produce the result.

5. Comparable

Comparable is an Interface, and it makes the classes comparable to its instances.

To compare the two instances of the same class, Comparable interface needs to be implemented, and the method compareTo() needs to be overridden. The classes that implement this interface, its list of objects are sorted automatically using the method Collections.sort() and Arrays.sort().

Code:

ArrayList<Employee> list = new ArrayList<>();
// Adding the instance objects of class Employee in list
list.add(new   Employee(10,   "Akshay")));
list.add(new      Employee(40,      "Bob")));
list.add(new  Employee(20,  "Priyansh")));
list.add(new  Employee(50,   "Chandni")));
list.add(new Employee(70, "Yashi")));
Collections.sort(list);
// Printing the sorted list on Console
System.out.println(list);
登录后复制

Output:

Java 中的排序

Conclusion

The Sorting in Java methods used in Java for multiple scenarios of Arrays and Collections are explained above. A programmer needs to keep in mind how the sort() method should be used for different Collection types. With Java 8, sorting can also be done through Lambdas to implement the Comparator interface, which makes the sorting easier. Though it is a bit difficult to learn all of them, it can be easy working with them if all the basic concepts of Java, especially data streaming, Arrays, and Collections, are clear. Though sorting Algorithms are evergreen and can be easily implemented in Java-like other programming languages, they have varying complexity, and the in-built function sort() of Java makes things easier if the basic concepts are learned by heart.

以上是Java 中的排序的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板