> Java > java지도 시간 > 본문

Java에서 정렬

王林
풀어 주다: 2024-08-30 15:29:35
원래의
427명이 탐색했습니다.
  • Java의 정렬은 기본적으로 특정 순서로 어딘가에 저장된 요소 그룹을 정렬하는 것입니다. 이 순서는 오름차순이거나 내림차순일 수 있습니다. 실시간 프로그래밍에는 요소를 정렬해야 하는 많은 시나리오가 있습니다. 정렬된 경우 배열 인덱스로 요소를 직접 쉽게 검색할 수 있으므로 특정 요소를 쉽게 검색할 수 있기 때문입니다. 정렬해야 하는 요소는 배열이나 컬렉션에 저장할 수 있습니다. 컬렉션은 Java와 유사한 세트, 트리, 맵, 힙, 목록 등의 다양한 유형으로 구성되지만, 배열과 같은 버블 정렬 힙 정렬, 삽입 정렬의 요소를 정렬하는 데 사용되는 다양한 유형의 정렬 알고리즘이 있습니다. , 선택정렬, 병합정렬 등
  • 프로그래머는 다양한 알고리즘을 사용하여 특정 요구 사항과 알고리즘의 복잡성에 따라 요소를 정렬합니다. 이러한 정렬 알고리즘은 다양한 루프와 변수를 사용하여 반복하여 구현됩니다. 배열의 요소를 정렬하기 위해 정렬 알고리즘을 사용하는 것 외에도 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 DOC에 따르면 Array.sort는 이중 피벗이며 단일 피벗 Quick Sort보다 상대적으로 훨씬 빠른 Quicksort를 사용합니다.
  • 이것의 가장 큰 장점 중 하나는 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으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!