티스토리 뷰
버블 정렬
import java.util.Arrays;
public class BubbleSort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[][] terms = { { "java", "php", "ruby", "csharp", "dotnet", "perl" },
{ "google", "apple", "oracle", "microsoft", "sun" },
{ "http", "web", "dns", "net", "protocol", "packet", "ip" },
{ "london", "madrid", "berlin", "ankara", "astana" } };
// The cycle time will put the biggest that number in the I That is the highest one .
//That is why the algorithm called Bubble Sort, because every time like bubbles rise.
for(int i =terms.length-1;i>=0;--i)
{
//The cycle time will traverse 0--(i-1),And when comparing the size of the adjacent two.
//they will be big like bubbles rise up, and is actually exchange two object
for(int j=0;j<=i-1;j++)
{
if (terms[j].length>terms[j+1].length) {
String[] term= terms[j];
terms[j] = terms[j+1];
terms[j+1]= term;
}
}
}
for (String[] term : terms) {
System.out.println(Arrays.toString(term) + ", length: " + term.length);
}
}
}
-------------------java.util.Arrays.sort(...)
( Arrays 클래스 API 링크 )를 사용하십시오 . 메서드 오버로드 중 하나는 Comparator 매개 변수와 함께 배열 매개 변수를 가져옵니다. Comparator의 compare(...)
메서드 에서 하위 배열 의 길이 를 비교합니다 .
예 :
Arrays.sort(terms, (a1, a2) -> Integer.compare(a1.length, a2.length));
예 :
import java.util.Arrays;
public class Sort2DArrays {
public static void main(String[] args) {
String[][] terms = { { "java", "php", "ruby", "csharp", "dotnet", "perl" },
{ "google", "apple", "oracle", "microsoft", "sun" },
{ "http", "web", "dns", "net", "protocol", "packet", "ip" },
{ "london", "madrid", "berlin", "ankara", "astana" } };
Arrays.sort(terms, (a1, a2) -> Integer.compare(a1.length, a2.length));
for (String[] term : terms) {
System.out.println(Arrays.toString(term) + ", length: " + term.length);
}
}
}
출처
https://stackoverflow.com/questions/39939997
댓글