logo

Java에서 문자열 배열을 정렬하는 방법

프로그래밍에서는 정렬 의 요소를 넣기 때문에 중요합니다. 정렬 특정 순서로. 널리 사용되는 순서 알파벳 순서입니다 또는 자연의 질서 . 정렬은 데이터를 표준화(표준 형식으로 변환하는 프로세스)하고 사람이 읽을 수 있는 형식을 생성하는 데 사용됩니다. 이 섹션에서는 다음 내용을 학습합니다. Java에서 문자열 배열을 정렬하는 방법 사용하여 사용자 정의 논리 그리고 배열. 종류() 방법

Java에서 문자열 배열을 정렬하는 방법에는 두 가지가 있습니다.

  • 사용 사용자 정의 논리
  • 사용하여 배열.정렬() 방법

사용자 정의 논리 사용

각 요소를 나머지 요소와 비교하여 문자열 배열을 정렬할 수 있습니다. 다음 예에서도 동일한 작업을 수행했습니다. 우리는 두 개의 for 루프를 사용했습니다. 내부(두 번째) for 루프는 비교에서 반복을 방지합니다. 조건 (countries[i].compareTo(countries[j])>0)이 0보다 참인 경우 스와핑을 수행하고 배열을 정렬합니다.

최소 최대

SortStringArrayExample1.java

 import java.util.Arrays; public class SortStringArrayExample1 { public static void main(String args[]) { //defining an array of type String String[] countries = {&apos;Zimbabwe&apos;, &apos;South-Africa&apos;, &apos;India&apos;, &apos;America&apos;, &apos;Yugoslavia&apos;, &apos; Australia&apos;, &apos;Denmark&apos;, &apos;France&apos;, &apos;Netherlands&apos;, &apos;Italy&apos;, &apos;Germany&apos;}; int size = countries.length; //logic for sorting for(int i = 0; i<size-1; i++) { for (int j="i+1;" j0) swapping array elements string temp="countries[i];" countries[i]="countries[j];" countries[j]="temp;" } prints the sorted in ascending order system.out.println(arrays.tostring(countries)); < pre> <p> <strong>Output:</strong> </p> <pre> [ Australia, America, Denmark, France, Germany, India, Italy, Netherlands, South-Africa, Yugoslavia, Zimbabwe] </pre> <h3>Using the Arrays.sort() Method</h3> <p>In Java, <strong>Arrays</strong> is the class defined in the java.util package that provides <strong>sort()</strong> method to sort an array in ascending order. It uses <strong>Dual-Pivot Quicksort algorithm</strong> for sorting. Its complexity is <strong>O(n log(n))</strong> . It is a <strong>static</strong> method that parses an <strong>array</strong> as a parameter and does not return anything. We can invoke it directly by using the class name. It accepts an array of type int, float, double, long, char, byte.</p> <p> <strong>Syntax:</strong> </p> <pre> public static void sort(int[] a) </pre> <p>Where <strong>a</strong> is an array to be short.</p> <h4>Note: Like the Arrays class, the Collections class also provides the sort() method to sort the array. But there is a difference between them. The sort() method of the Arrays class works for primitive type while the sort() method of the Collections class works for objects Collections, such as LinkedList, ArrayList, etc.</h4> <p>We can perform sorting in the following ways:</p> <ul> <tr><td>Ascending Order</td> or <strong>Alphabetical Order</strong> or <strong>Natural Order</strong>  </tr><tr><td>Descending Order</td> or <strong>Reverse Natural Order</strong>  </tr></ul> <h3>Sort String Array in Ascending Order or Alphabetical Order</h3> <p>The <strong>ascending order</strong> arranges the elements in the lowest to highest order. It is also known as <strong>natural order</strong> or <strong>alphabetical order</strong> .</p> <p>Let&apos;s sort an array using the sort() method of the Arrays class.</p> <p> <strong>SortStringArrayExample2.java</strong> </p> <pre> import java.util.Arrays; public class SortStringArrayExample2 { public static void main(String args[]) { //defining an array of type string String[] countries = {&apos;Wood apple&apos;, &apos;Blackberry&apos;, &apos;Date&apos;, &apos;Naseberry&apos;, &apos;Tamarind&apos;, &apos;Fig&apos;, &apos;Mulberry&apos;, &apos;Apple&apos;, &apos;Plum&apos;, &apos;Orange&apos;, &apos;Custard apple&apos;, &apos;Apricot&apos;}; //sorts string array in alphabetical order or ascending order Arrays.sort(countries); //prints the sorted string array in ascending order System.out.println(Arrays.toString(countries)); } } </pre> <p> <strong>Output:</strong> </p> <pre> [Apple, Apricot, Blackberry, Custard apple, Date, Fig, Mulberry, Naseberry, Orange, Plum, Tamarind, Wood apple] </pre> <h3>Sort String Array in Descending Order or Reverse Natural Order</h3> <h3>Using the reverseOrder() Method</h3> <p>Java <strong>Collections</strong> class provides the <strong>reverseOrder()</strong> method to sort the array in reverse-lexicographic order. It is a static method, so we can invoke it directly by using the class name. It does not parse any parameter. It returns a <strong>comparator</strong> that imposes the reverse of the natural ordering (ascending order).</p> <p>It means that the array sorts elements in the ascending order by using the sort() method, after that the reverseOrder() method reverses the natural ordering, and we get the sorted array in descending order.</p> <p> <strong>Syntax:</strong> </p> <pre> public static Comparator reverseOrder() </pre> <p>Suppose, a[] is an array to be sort in the descending order. We will use the reverseOrder() method in the following way:</p> <pre> Arrays.sort(a, Collections.reverseOrder()); </pre> <p>Let&apos;s sort a string array in the descending order.</p> <p> <strong>SortStringArrayExample3.java</strong> </p> <pre> import java.util.*; public class SortStringArrayExample1 { public static void main(String args[]) { //defining an array of type String String[] countries = {&apos;Zimbabwe&apos;, &apos;South-Africa&apos;, &apos;India&apos;, &apos;America&apos;, &apos;Yugoslavia&apos;, &apos; Australia&apos;, &apos;Denmark&apos;, &apos;France&apos;, &apos;Netherlands&apos;, &apos;Italy&apos;, &apos;Germany&apos;}; //sorts array in descending order Arrays.sort(countries, Collections.reverseOrder()); //prints the sorted string array in descending order System.out.println(Arrays.toString(countries)); } } </pre> <p> <strong>Output:</strong> </p> <pre> [Zimbabwe, Yugoslavia, South-Africa, Netherlands, Italy, India, Germany, France, Denmark, America, Australia] </pre> <hr></size-1;>

Arrays.sort() 메서드 사용

자바에서는 배열 다음을 제공하는 java.util 패키지에 정의된 클래스입니다. 종류() 배열을 오름차순으로 정렬하는 방법. 그것은 사용한다 듀얼 피벗 퀵소트 알고리즘 정렬용. 그 복잡성은 O(n로그(n)) . 이것은 공전 구문 분석하는 메소드 정렬 매개변수로 사용되며 아무것도 반환하지 않습니다. 클래스 이름을 사용하여 직접 호출할 수 있습니다. int, float, double, long, char, byte 유형의 배열을 허용합니다.

통사론:

 public static void sort(int[] a) 

어디 짧은 배열입니다.

참고: Arrays 클래스와 마찬가지로 Collections 클래스도 배열을 정렬하는 sort() 메서드를 제공합니다. 그러나 그들 사이에는 차이점이 있습니다. Arrays 클래스의 sort() 메서드는 기본 유형에 대해 작동하는 반면 Collections 클래스의 sort() 메서드는 LinkedList, ArrayList 등과 같은 컬렉션 개체에 대해 작동합니다.

다음과 같은 방법으로 정렬을 수행할 수 있습니다.

    오름차순또는 알파벳 순서 또는 자연의 질서 내림차순또는 역 자연 순서

오름차순 또는 알파벳순으로 문자열 배열 정렬

그만큼 오름차순 요소를 가장 낮은 순서에서 가장 높은 순서로 정렬합니다. 그것은 또한로 알려져 있습니다 자연의 질서 또는 알파벳 순서 .

Arrays 클래스의 sort() 메서드를 사용하여 배열을 정렬해 보겠습니다.

SortStringArrayExample2.java

자바에서 목록 생성
 import java.util.Arrays; public class SortStringArrayExample2 { public static void main(String args[]) { //defining an array of type string String[] countries = {&apos;Wood apple&apos;, &apos;Blackberry&apos;, &apos;Date&apos;, &apos;Naseberry&apos;, &apos;Tamarind&apos;, &apos;Fig&apos;, &apos;Mulberry&apos;, &apos;Apple&apos;, &apos;Plum&apos;, &apos;Orange&apos;, &apos;Custard apple&apos;, &apos;Apricot&apos;}; //sorts string array in alphabetical order or ascending order Arrays.sort(countries); //prints the sorted string array in ascending order System.out.println(Arrays.toString(countries)); } } 

산출:

 [Apple, Apricot, Blackberry, Custard apple, Date, Fig, Mulberry, Naseberry, Orange, Plum, Tamarind, Wood apple] 

내림차순 또는 역자연순으로 문자열 배열 정렬

reverseOrder() 메서드 사용

자바 컬렉션 수업은 역순으로() 배열을 역사전순으로 정렬하는 방법입니다. 이는 정적 메서드이므로 클래스 이름을 사용하여 직접 호출할 수 있습니다. 어떤 매개변수도 구문 분석하지 않습니다. 그것은 비교기 이는 자연 순서(오름차순)의 반대 순서를 적용합니다.

이는 배열이 sort() 메서드를 사용하여 오름차순으로 요소를 정렬한 후 reverseOrder() 메서드가 자연 순서를 반대로 하여 내림차순으로 정렬된 배열을 얻는다는 의미입니다.

통사론:

 public static Comparator reverseOrder() 

a[]는 내림차순으로 정렬할 배열이라고 가정합니다. 다음과 같은 방법으로 reverseOrder() 메서드를 사용합니다.

 Arrays.sort(a, Collections.reverseOrder()); 

문자열 배열을 내림차순으로 정렬해 보겠습니다.

테스트 mockito 준비

SortStringArrayExample3.java

 import java.util.*; public class SortStringArrayExample1 { public static void main(String args[]) { //defining an array of type String String[] countries = {&apos;Zimbabwe&apos;, &apos;South-Africa&apos;, &apos;India&apos;, &apos;America&apos;, &apos;Yugoslavia&apos;, &apos; Australia&apos;, &apos;Denmark&apos;, &apos;France&apos;, &apos;Netherlands&apos;, &apos;Italy&apos;, &apos;Germany&apos;}; //sorts array in descending order Arrays.sort(countries, Collections.reverseOrder()); //prints the sorted string array in descending order System.out.println(Arrays.toString(countries)); } } 

산출:

 [Zimbabwe, Yugoslavia, South-Africa, Netherlands, Italy, India, Germany, France, Denmark, America, Australia]