java.util.Collections.sort() 메소드는 java.util.Collections 클래스에 있습니다. 지정된 항목에 있는 요소를 정렬하는 데 사용됩니다. 목록 오름차순으로 컬렉션이 표시됩니다. 그것은 유사하게 작동합니다 java.util.Arrays.sort() 방법이지만 Array의 요소와 연결된 목록 대기열 및 그 안에 있는 더 많은 요소를 정렬할 수 있는 것보다 낫습니다.
public static void sort(List myList)
myList : A List type object we want to sort.
This method doesn't return anything
예:
Let us suppose that our list contains
{'Geeks For Geeks' 'Friends' 'Dear' 'Is' 'Superb'}
After using Collection.sort() we obtain a sorted list as
{'Dear' 'Friends' 'Geeks For Geeks' 'Is' 'Superb'}
ArrayList를 오름차순으로 정렬
JAVA
// Java program to demonstrate working of Collections.sort() import java.util.*; public class Collectionsorting { public static void main(String[] args) { // Create a list of strings ArrayList<String> al = new ArrayList<String>(); al.add('Geeks For Geeks'); al.add('Friends'); al.add('Dear'); al.add('Is'); al.add('Superb'); /* Collections.sort method is sorting the elements of ArrayList in ascending order. */ Collections.sort(al); // Let us print the sorted list System.out.println('List after the use of' + ' Collection.sort() :n' + al); } }
산출
List after the use of Collection.sort() : [Dear Friends Geeks For Geeks Is Superb]
시간 복잡도 : Collections.sort()의 시간 복잡도가 O(nlog(n))이므로 O(N log N)입니다.
보조 공간 : ㅇ(1)
ArrayList를 내림차순으로 정렬
JAVA// Java program to demonstrate working of Collections.sort() // to descending order. import java.util.*; public class Collectionsorting { public static void main(String[] args) { // Create a list of strings ArrayList<String> al = new ArrayList<String>(); al.add('Geeks For Geeks'); al.add('Friends'); al.add('Dear'); al.add('Is'); al.add('Superb'); /* Collections.sort method is sorting the elements of ArrayList in ascending order. */ Collections.sort(al Collections.reverseOrder()); // Let us print the sorted list System.out.println('List after the use of' + ' Collection.sort() :n' + al); } }
산출
List after the use of Collection.sort() : [Superb Is Geeks For Geeks Friends Dear]
시간 복잡도: Collections.sort()의 시간 복잡도는 O(N log N)이므로 O(nlog(n))입니다.
보조 공간: 오(1)
사용자 정의 기준에 따라 ArrayList를 정렬합니다. 우리는 사용할 수 있습니다 비교기 인터페이스 이 목적을 위해.
Java// Java program to demonstrate working of Comparator // interface and Collections.sort() to sort according // to user defined criteria. import java.util.*; import java.lang.*; import java.io.*; // A class to represent a student. class Student { int rollno; String name address; // Constructor public Student(int rollno String name String address) { this.rollno = rollno; this.name = name; this.address = address; } // Used to print student details in main() public String toString() { return this.rollno + ' ' + this.name + ' ' + this.address; } } class Sortbyroll implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student a Student b) { return a.rollno - b.rollno; } } // Driver class class Main { public static void main (String[] args) { ArrayList<Student> ar = new ArrayList<Student>(); ar.add(new Student(111 'bbbb' 'london')); ar.add(new Student(131 'aaaa' 'nyc')); ar.add(new Student(121 'cccc' 'jaipur')); System.out.println('Unsorted'); for (int i=0; i<ar.size(); i++) System.out.println(ar.get(i)); Collections.sort(ar new Sortbyroll()); System.out.println('nSorted by rollno'); for (int i=0; i<ar.size(); i++) System.out.println(ar.get(i)); } }
산출
Unsorted 111 bbbb london 131 aaaa nyc 121 cccc jaipur Sorted by rollno 111 bbbb london 121 cccc jaipur 131 aaaa nyc
배열.정렬() 대 Collections.sort() Arrays.sort는 기본 데이터 유형일 수 있는 배열에도 작동합니다. 컬렉션 .sort()는 다음과 같은 객체 컬렉션에 대해 작동합니다. 배열목록 링크드리스트 등. 주어진 배열 항목의 ArrayList를 생성한 후 Collections.sort()를 사용하여 배열을 정렬할 수 있습니다.
// Using Collections.sort() to sort an array import java.util.*; public class Collectionsort { public static void main(String[] args) { // create an array of string objs String domains[] = {'Practice' 'Geeks' 'Code' 'Quiz'}; // Here we are making a list named as Collist List colList = new ArrayList(Arrays.asList(domains)); // Collection.sort() method is used here // to sort the list elements. Collections.sort(colList); // Let us print the sorted list System.out.println('List after the use of' + ' Collection.sort() :n' + colList); } }
산출
List after the use of Collection.sort() : [Code Geeks Practice Quiz]
Arrays.sort() 대 Collections.sort() 시간 복잡도:
Arrays.sort()는 일반적으로 기존 Quicksort 알고리즘보다 빠른 O(N.log N)의 시간 복잡도를 제공하는 Dual-Pivot Quicksort 알고리즘을 사용합니다. 반면에 Collections.sort()는 목록 요소의 배열을 생성하고 적응형 병합 정렬 알고리즘을 사용하여 요소를 정렬하고 목록을 반복하여 각 요소를 올바른 위치에 배치합니다. 따라서 int char double 등과 같은 기본 데이터 유형의 경우 Arrays.sort()는 Collections.sort()보다 훨씬 더 시간 효율적인 것으로 입증되었습니다. 기본 데이터 유형과 관련된 문제는 더 나은 최적화를 위해 Arrays.sort()를 사용하여 해결해야 합니다.
다음은 차이점을 보여주는 코드입니다.
Java/*package whatever //do not write package name here */ import java.io.*; import java.util.*; class GFG { public static void main (String[] args) { int len = 5000000; // creating a large test array int[] arr = new int[len]; for (int i = len; i > 0; i--) arr[len - i] = i; // creating a large test arraylist ArrayList<Integer> list = new ArrayList<>(); for (int i = len; i > 0; i--) list.add(i); // calculating time used by arrays.sort() long startA = System.currentTimeMillis(); Arrays.sort(arr); long stopA = System.currentTimeMillis(); // calculating time used by collections.sort() long startAL = System.currentTimeMillis(); Collections.sort(list); long stopAL = System.currentTimeMillis(); System.out.println('Time taken by Arrays.sort(): ' + (stopA - startA)); System.out.println('Time taken by Collections.sort(): ' + (stopAL - startAL)); } } // This code is contributed by godcoder28
산출
Time taken by Arrays.sort(): 29 Time taken by Collections.sort(): 42
이 기사는 존경받는 괴짜들에게 유용하기를 바랍니다. .