辞書式順序(辞書順)で要素をソートするJavaプログラム
この記事では、Javaで配列の要素を辞書式順序で並べ替える方法を理解します。辞書式順序は、辞書のアルファベット順をシーケンスに一般化したものです。
以下は同じのデモンストレーションです-
入力
入力が-
であると仮定しますAplha Beta Gamma Delta
出力
必要な出力は-
になりますAplha Beta Delta Gamma
アルゴリズム
Step1- Start Step 2- Declare three integers: I, j, array_length Step 3- Declare a string array Step 4- Prompt the user to enter the array_length value/ define the array_length Step 5- Prompt the user to enter the words of the string array/ define the string array Step 4- Read the values Step 5- Run a for-loop, using the swap method, arrange the words using the compareTo function. Store the values. Step 6- Display the result Step 7- Stop
例1
public class Main {
public static void main(String[] args) {
String[] my_input = { "Aplha", "Beta", "Gamma", "Delta" }; ;
int i, j, array_length;
array_length = 4;
System.out.println("The array of string is defined as ");
for(i = 0; i < array_length; i++) {
System.out.println(my_input[i]);
}
for(i = 0; i < array_length - 1; ++i) {
for (j = i + 1; j < array_length; ++j) {
if (my_input[i].compareTo(my_input[j]) > 0) {
String temp = my_input[i];
my_input[i] = my_input[j];
my_input[j] = temp;
}
}
}
System.out.println("The words in lexicographical order is:");
for(i = 0; i < 4; i++) {
System.out.println(my_input[i]);
}
}
} 出力
The array of string is defined as Aplha Beta Gamma Delta The words in lexicographical order is: Aplha Beta Delta Gamma
例2
import java.io.*;
public class LexicographicalOrder {
public static void
sortData(String my_array[]){
for (int i = 0; i < my_array.length; i++) {
for (int j = i + 1; j < my_array.length; j++) {
if (my_array[i].compareToIgnoreCase(my_array[j])< 0) {
String my_temp = my_array[i];
my_array[i] = my_array[j];
my_array[j] = my_temp;
}
}
}
}
public static void printData(String my_array[]){
for (String my_string : my_array)
System.out.print(my_string + " ");
System.out.println();
}
public static void main(String[] args){
String my_array[] = { "Aplha", "Beta", "Gamma", "Delta" };
System.out.println("Required packages have been imported");
System.out.println("The Lexicographical Order data is");
sortData(my_array);
printData(my_array);
}
} 出力
Required packages have been imported The Lexicographical Order data is Aplha Beta Delta Gamma
-
ソートをカウントするためのJavaプログラム
カウントソートは、個別のキー値を持つオブジェクトの数をカウントします。例を見てみましょう- 注 −以下のコードは、負の数でも使用できます。 例 import java.util.*; public class Demo{ static void count_sort(int[] arr){ int max_val = Arrays.stream(arr).max().getAsInt(); int min_val = Arrays.stream(arr).min().getAsInt
-
カクテルソート用のJavaプログラム
カクテルソートは、要素が左から右に繰り返され、最大の要素が最初に正しい位置に移動されるバブルソートとは対照的に機能します。シェーカーソートでは、要素が交互に両方向(左と右)に繰り返されます。 以下は、カクテルソートのプログラムです- 例 public class Demo{ static int temp; static void Cocktail(int a[], int n){ boolean swap = true; int begin = 0,i;