내 정렬 루프가하지 말아야 할 요소를 추가하는 것처럼 보이는 이유는 무엇입니까?
.NET을 사용하여 문자열 배열을 정렬하려고합니다 compareTo()
. 이것은 내 코드입니다.
static String Array[] = {" Hello ", " This ", "is ", "Sorting ", "Example"};
String temp;
public static void main(String[] args)
{
for (int j=0; j<Array.length;j++)
{
for (int i=j+1 ; i<Array.length; i++)
{
if (Array[i].compareTo(Array[j])<0)
{
String temp = Array[j];
Array[j] = Array[i];
Array[i] = temp;
}
}
System.out.print(Array[j]);
}
}
이제 출력은 다음과 같습니다.
Hello This Example Sorting is
결과를 얻었지만 원하는 결과가 아닙니다.
Hello This Example Is Sorting
문자열 배열을 올바르게 정렬하기 위해 코드를 어떻게 조정할 수 있습니까?
출력이 정확합니다. 처음에는 "Hello"및 "This"의 흰색 문자를 표시하십시오.
또 다른 문제는 방법론입니다. Arrays.sort()
방법을 사용하십시오 :
String[] strings = { " Hello ", " This ", "Is ", "Sorting ", "Example" };
Arrays.sort(strings);
산출:
Hello
This
Example
Is
Sorting
여기서 배열 "is"의 세 번째 요소는 "Is"여야합니다. 그렇지 않으면 정렬 후 마지막에 올 것입니다. 정렬 방법은 내부적으로 ASCII 값을 사용하여 요소를 정렬하기 때문입니다.
여기에 게시 된 대체 솔루션 (정확함)을 제외하고는 아무도 실제로 코드의 문제점을 해결하여 질문에 답변하지 않았습니다.
선택 정렬 알고리즘 을 구현하려는 것 같습니다 . 여기서 정렬이 어떻게 작동하는지에 대한 자세한 내용은 다루지 않겠지 만 참조를 위해 몇 가지 링크를 포함했습니다. =)
코드 구문은 정확했지만 논리적으로 잘못되었습니다. 각 문자열을 그 뒤에 오는 문자열과 비교 하여 문자열 을 부분적으로 정렬 했습니다 . 수정 된 버전은 다음과 같습니다 ( "잘못된"부분을 설명하기 위해 원본 코드를 그대로 유지했습니다).
static String Array[]={" Hello " , " This " , "is ", "Sorting ", "Example"};
String temp;
//Keeps track of the smallest string's index
int shortestStringIndex;
public static void main(String[] args)
{
//I reduced the upper bound from Array.length to (Array.length - 1)
for(int j=0; j < Array.length - 1;j++)
{
shortestStringIndex = j;
for (int i=j+1 ; i<Array.length; i++)
{
//We keep track of the index to the smallest string
if(Array[i].trim().compareTo(Array[shortestStringIndex].trim())<0)
{
shortestStringIndex = i;
}
}
//We only swap with the smallest string
if(shortestStringIndex != j)
{
String temp = Array[j];
Array[j] = Array[shortestStringIndex];
Array[shortestStringIndex] = temp;
}
}
}
추가 읽기
이 접근 방식의 문제는 점근 적 복잡성이 O (n ^ 2) 입니다. 간단히 말해서, 어레이의 크기가 커짐에 따라 (무한대에 가까워짐) 매우 느려집니다. quicksort 와 같은 더 나은 데이터 정렬 방법에 대해 읽어 볼 수 있습니다 .
이 줄 대신
if(Array[i].compareTo(Array[j])<0)
이 줄을 사용
if(Array[i].trim().compareTo(Array[j].trim())<0)
그리고 당신은 갈 수 있습니다. 현재 코드가 작동하지 않는 이유는 이미 다른 사용자가 설명했습니다. 위의 교체는 적용 할 수있는 몇 가지 해결 방법 중 하나입니다.
나는 이것이 늦은 답장이라는 것을 알고 있지만 누군가를 도울 수 있습니다.
공백 제거는 trim () 함수를 사용하여 수행 할 수 있습니다. 그 후에 대소 문자를 구분하는 방식으로 배열을 정렬하려면 다음을 사용할 수 있습니다.
Arrays.sort(yourArray);
대소 문자를 구분하지 않는 경우 :
Arrays.sort(yourArray,String.CASE_INSENSITIVE_ORDER);
도움이 되었기를 바랍니다!
Java 8 부터는 parallelSort
많은 요소를 포함하는 배열이있는 경우 유용하게 사용할 수도 있습니다 .
예:
public static void main(String[] args) {
String[] strings = { "x", "a", "c", "b", "y" };
Arrays.parallelSort(strings);
System.out.println(Arrays.toString(strings)); // [a, b, c, x, y]
}
대소 문자 를 무시하려면 다음을 사용할 수 있습니다.
public static void main(String[] args) {
String[] strings = { "x", "a", "c", "B", "y" };
Arrays.parallelSort(strings, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
});
System.out.println(Arrays.toString(strings)); // [a, B, c, x, y]
}
그렇지 않으면 B
이전이 a
됩니다.
비교 중에 후행 공백 을 무시하려면 다음을 사용할 수 있습니다 trim()
.
public static void main(String[] args) {
String[] strings = { "x", " a", "c ", " b", "y" };
Arrays.parallelSort(strings, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.trim().compareTo(o2.trim());
}
});
System.out.println(Arrays.toString(strings)); // [ a, b, c , x, y]
}
참조 :
- https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
- Arrays.sort ()와 Arrays.parallelSort ()의 차이점
- http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/Arrays.java?av=f
" Hello " , " This " , "is ", "Sorting ", "Example"
우선 " Hello "
및 " This "
에 공백 을 제공했습니다. 공백 은 유니 코드의 알파벳 문자보다 값이 낮으므로 먼저 인쇄됩니다. (나머지 문자는 알파벳순으로 정렬되었습니다).
이제 대문자는 유니 코드의 소문자보다 낮은 값을 가지므로 "예제"와 "정렬"이 인쇄되고 마지막 "is "
에 가장 높은 값 이 인쇄 됩니다.
사용하는 경우 :
if (Array[i].compareToIgnoreCase(Array[j]) < 0)
당신은 얻을 것이다 :
Example Hello is Sorting This
당신이 찾고 있던 결과물이라고 생각합니다.
To begin with, your problem is that you use the method `compareTo() which is case sensitive. That means that the Capital letters are sorted apart from the lower case. The reason is that it translated in Unicode where the capital letters are presented with numbers which are less than the presented number of lower case. Thus you should use `compareToIgnoreCase()` as many also mentioned in previous posts.
This is my full example approach of how you can do it effecively
After you create an object of the Comparator you can pass it in this version of `sort()` which defined in java.util.Arrays.
static<T>void sort(T[]array,Comparator<?super T>comp)
take a close look at super. This makes sure that the array which is passed into is combatible with the type of comparator.
The magic part of this way is that you can easily sort the array of strings in Reverse order you can easily do by:
return strB.compareToIgnoreCase(strA);
import java.util.Comparator;
public class IgnoreCaseComp implements Comparator<String> {
@Override
public int compare(String strA, String strB) {
return strA.compareToIgnoreCase(strB);
}
}
import java.util.Arrays;
public class IgnoreCaseSort {
public static void main(String[] args) {
String strs[] = {" Hello ", " This ", "is ", "Sorting ", "Example"};
System.out.print("Initial order: ");
for (String s : strs) {
System.out.print(s + " ");
}
System.out.println("\n");
IgnoreCaseComp icc = new IgnoreCaseComp();
Arrays.sort(strs, icc);
System.out.print("Case-insesitive sorted order: ");
for (String s : strs) {
System.out.print(s + " ");
}
System.out.println("\n");
Arrays.sort(strs);
System.out.print("Default, case-sensitive sorted order: ");
for (String s : strs) {
System.out.print(s + " ");
}
System.out.println("\n");
}
}
run:
Initial order: Hello This is Sorting Example
Case-insesitive sorted order: Hello This Example is Sorting
Default, case-sensitive sorted order: Hello This Example Sorting is
BUILD SUCCESSFUL (total time: 0 seconds)
Alternative Choice
The method compareToIgnoreCase()
, although it works well with many occasions(just like compare string in english),it will wont work well with all languages and locations. This automatically makes it an unfit choice for use. To make sure that it will be suppoorted everywhere you should use compare()
from java.text.Collator.
You can find a collator for your location by calling the method getInstance()
. After that you should set this Collator's strength property. This can be done with the setStrength()
method together with Collator.PRIMARY
as parameter. With this alternative choise the IgnocaseComp can be written just like below. This version of code will generate the same output independently of the location
import java.text.Collator;
import java.util.Comparator;
//this comparator uses one Collator to determine
//the right sort usage with no sensitive type
//of the 2 given strings
public class IgnoreCaseComp implements Comparator<String> {
Collator col;
IgnoreCaseComp() {
//default locale
col = Collator.getInstance();
//this will consider only PRIMARY difference ("a" vs "b")
col.setStrength(Collator.PRIMARY);
}
@Override
public int compare(String strA, String strB) {
return col.compare(strA, strB);
}
}
'developer tip' 카테고리의 다른 글
행렬에서 주어진 값의 요소 수를 어떻게 계산할 수 있습니까? (0) | 2020.10.31 |
---|---|
다형성의 이점 (0) | 2020.10.31 |
OnItemClickListener android를 사용한 ListView (0) | 2020.10.31 |
HttpClient 4.0.1-연결 해제 방법? (0) | 2020.10.31 |
순서가 지정되지 않은 목록의 항목 뒤에 파이프 구분 기호 추가 (0) | 2020.10.31 |