2018-3-31 TIL 배열의 정렬 및 탐색

Java Arrays

배열의 정렬

package yoon;
import java.util.Arrays;

class Person implements Comparable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Object o) {
        Person p = (Person)o;
        if(this.age > p.age)
            return 1; // 인저로 전달된 o가 작다면 1반환
        else if(this.age < p.age)
            return -1;
        else
            return 0;
    }

    @Override
    public String toString() {
        return name + ": " + age;
    }
}

public class ArrayObjSort {
    public static void main(String [] args) {
        Person [] ar = new Person[3];
        ar[0] = new Person("Lee", 29);
        ar[1] = new Person("Goo", 15);
        ar[2] = new Person("Soo", 37);

        Arrays.sort(ar);
        for(Person p : ar)
            System.out.println(p);
    }
}
//result
Goo: 15
Lee: 29
Soo: 37

배열의 탐색

package yoon;

import java.util.Arrays;

public class ArraySearch {
    public static void main(String [] args) {
        int [] ar = {33, 55, 11, 44, 22};
        Arrays.sort(ar);

        for(int n : ar)
            System.out.print(n + "\t");
        System.out.println();

        int idx = Arrays.binarySearch(ar, 33); // ar에서 33을 찾아라
        System.out.println("Index of 33 : " + idx);
    }
}
//result
11	22	33	44	55
Index of 33 : 2
Written on March 31, 2018