코틀린 알고리즘, 정렬

oune·2022년 10월 31일
0

알고리즘

목록 보기
3/5
post-thumbnail

sorted(), sort()

// 불변 자료구조를 정렬하여 리턴하는 함수
val sorted = list.sorted()

// 가변 자료구조를 정렬함, 리턴하지 않음.
val list = mutableListOf(5, 4, 3, 2, 1)
list.sort()

오름차순과 내림차순

// 불변
immutablelist.sorted() // 오름차순
immutablelist.sortedDescending() // 내림차순
immutablelist.sorted().reversed() // 내림차순

// 가변
mutablelist.sort() // 오름차순
mutablelist.sortDescending() // 내림차순
mutablelist.sort().revers() // 내림차순

sort는 기본적으로 오름차순으로 작동,

내부 구조

/**
 * Returns a list of all elements sorted descending according to their natural sort order.
 */
public fun IntArray.sortedDescending(): List<Int> {
    return copyOf().apply { sort() }.reversed()
}
/**
 * Returns a list of all elements sorted according to their natural sort order.
 */
public fun IntArray.sorted(): List<Int> {
    return toTypedArray().apply { sort() }.asList()
}

내부적으로 sortedDescending()은 sorted().reversed() 와 동일함.
https://github.com/JetBrains/kotlin/blob/f3385fbdcb8b9dc29661a8a4973c855cdcf73767/libraries/stdlib/common/src/generated/_Arrays.kt#L6587

sortedBy(), sortedWith()

sortedBy()

// 가변
val list = mutableListOf(Pair(1, 2), Pair(2, 3), Pair(3, 4))
list.sortBy { it.first } // 첫번째 요소기준으로 정렬
list.sortBy { it.second } // 두번째 요소기준으로 정렬
list.sortBy { it.first - it.second } // 첫번째에서 두번째의 차 기준으로 정렬

// 불변
val list = listOf(Pair(1, 2), Pair(2, 3), Pair(3, 4))
list.sortedBy { it.first } // 첫번째 요소기준으로 정렬
list.sortedBy { it.second } // 두번째 요소기준으로 정렬
list.sortedBy { it.first - it.second } // 첫번째에서 두번째의 차 기준으로 정렬

sortedWith()

val applicants = Array(applicantCnt) {
    val (paper, meeting) = readLine().split(" ").map { it.toInt() }
    Score(paper, meeting)
}
// paper기준으로 정렬한 이후 meeting 으로 정렬
val sorted = applicants.sortedWith(
    compareBy<Score> { it.paper }.thenBy {
        it.meeting
    }
)

Comparator를 이용하여 정렬

compareBy()

compareBy<Score> { it.paper }

paper기준으로 Comparator를 생성

thenBy()

compareBy<Score> { it.paper }.thenBy {
        it.meeting
    }

Comparator가 같은 경우에 비교할 기준을 생성

우선순위큐

val que = PriorityQueue ( compareBy<Pair<Int, Int>> { (_, cost) -> cost} )

Comparator를 이용하여 우선순위큐 생성 가능

profile
어느새 신입 개발자

0개의 댓글