Java での並べ替え

王林
リリース: 2024-08-30 15:29:35
オリジナル
427 人が閲覧しました
  • Java での並べ替えは、基本的に、どこかに保存されている要素のグループを特定の順序で並べ替えることです。この順序は昇順でも降順でも構いません。リアルタイム プログラミングでは、要素をソートする必要がある多くのシナリオが発生します。ソートすると、配列のインデックスによって直接要素を簡単に取得できるため、特定の要素の検索も容易になります。並べ替える必要がある要素は、配列またはコレクションに格納できます。コレクションには、Java のようなセット、ツリー、マップ、ヒープ、リストなどの多くのタイプがありますが、配列のようなバブル ソート、ヒープ ソート、挿入ソートで要素をソートするために使用されるソート アルゴリズムにはさまざまなタイプがあります。 、選択ソート、マージソートなど
  • プログラマーは、特定の要件とアルゴリズムの複雑さに応じて、さまざまなアルゴリズムを使用して要素を並べ替えます。これらの並べ替えアルゴリズムは、さまざまなループと変数を使用して反復処理することによって実装されます。ソート アルゴリズムを使用して配列内の要素をソートする以外に、Java にはソート機能が組み込まれており、これが同じ処理に役立ちます。プログラマは大きなループに陥って複雑さを考慮する必要がありません。はい、お聞きのとおり、Java では sort() 関数は、配列またはコレクションに格納されている要素を並べ替えるために使用され、その複雑さは非常に少ない o(n(logn)) です。ただし、両方のメソッドの実装は少し異なります。

配列の構文:

Arrays.sort(array_name);
ログイン後にコピー

コレクション用

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

Collections.sort(array_name_list);
ログイン後にコピー
  • ここで、array_name と array_name_list は、並べ替える必要がある配列またはコレクションの名前です。
  • 配列は Java のクラスの名前です。
  • コレクションは Java のフレームワークです。
  • sort() は、Java で使用される組み込みの並べ替え関数です。

Java ではソートはどのように実行されますか?

次の点は次のとおりです:

  • 並べ替えアルゴリズムを使用すると、非効率的なアルゴリズムから効率的なアルゴリズムまでさまざまなアルゴリズムで並べ替えを実行することもできます。また、すべてのアルゴリズムには独自の時間と空間の複雑さがあります。
  • これらのアルゴリズムは非常に複雑なので、大量のデータを処理する必要がある実際のシナリオでは使用できない場合があります。
  • 上で述べたように、Java 組み込み関数では、sort() を使用して配列とコレクションのすべての要素を並べ替えます。公式の Java DOC によると、Array.sort はダブル ピボットのクイックソートを使用しており、シングル ピボットのクイック ソートよりも比較的高速です。
  • この最大の利点の 1 つは、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 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!