Algorithm

[Kotlin] 리스트 정렬

YOONJELLY 2024. 2. 1. 16:41

정렬

1) 기본 정렬

1. Immutable 리스트 기본 정렬

val list = listOf(20, 10, 40, 30, 50)
val sortedList = list.sorted()

println("List : $list")
println("SortedList : $sortedList")

// 결과
// List : [20, 10, 40, 30, 50]
// sortedList : [10, 20, 30, 40, 50]
  • 불변 리스트이므로 원본 리스트는 변경되지 않습니다.

2. Mutable 리스트 기본 정렬

val mutableList = MutableList(20, 10, 40, 30, 50)
mutableList.sort()

println("MutableList : $mutableList")

// 결과
// MutableList : [10, 20, 30, 40, 50]
  • 원본 리스트를 수정합니다.

 

2) 역순 정렬

1. Immutable 리스트 역순 정렬

val list = listOf(20, 10, 40, 30, 50)
val reversedSortedList = list.sorted().reversed()
println("reversedSortedList : $reversedSortedList")

// 결과
// reversedSortedList : [50, 40, 30, 20, 10]
  • 기본 정렬과 마찬가지로 원본 리스트는 변경되지 않으며 역순으로 변경된 새로운 리스트를 리턴합니다.

2. Mutable 리스트 역순 정렬

// Mutable List
val mutableList = mutableListOf(20, 10, 40, 30, 50)
mutableList.sort()
mutableList.reverse()
println("reversedMutableList : $mutableList")

// 결과
// reversedMutableList : [50, 40, 30, 20, 10]

 

3) 정렬 규칙 지정 - sortedWith(), sortWith()

1. Immutable 리스트 Comparator 지정

val list = listOf("aaaaa", "bbbb", "ccc", "dd", "e")
val lengthOrder = list.sortedWith(compareBy<String> { it.length })
println("Length Order : $lengthOrder")

// 결과
// Length Order : [e, dd, ccc, bbbb, aaaaa]

2. Mutable 리스트 Comparator 지정

val list = MutableListOf("aaaaa", "bbbb", "ccc", "dd", "e")
list.sortWith(compareBy<String> { it.length })
println("Length Order : $list")

// 결과
// Length Order : [e, dd, ccc, bbbb, aaaaa]

 

4) 정렬 규칙 지정 - sortedBy(), sortBy()

  • 리스트 요소가 내부에 여러 요소를 가지고 있을 때, 어떤 요소를 기준으로 정렬을 할 지 정하여 정렬을 수행합니다.

1. Immutable 리스트

val list = listOf("b" to 5, "a" to 10,  "d" to 7, "c" to 1)
sortedByFirst = list.sortedBy { it.first }
println("sortedByFirst : ${sortedByFirst}")

// 결과
// sortedByFirst : [(a, 10), (b, 5), (c, 1), (d, 7)]

2. Mutable 리스트

val mutableList = mutableListOf("b" to 5, "a" to 10,  "d" to 7, "c" to 1)
println("mutableList : $mutableList")

mutableList.sortBy { it.first }
println("sortByFirst : $mutableList")

mutableList.sortBy { it.second }
println("sortBySecond : $mutableList")

// 결과
// mutableList : [(b, 5), (a, 10), (d, 7), (c, 1)]
// sortByFirst : [(a, 10), (b, 5), (c, 1), (d, 7)]
// sortBySecond : [(c, 1), (b, 5), (d, 7), (a, 10)]