Posted at

kotlinでsortを使った配列練習

More than 1 year has passed since last update.


概要

kotlinで配列を使う練習を行うためバブルソート、挿入ソート、クイックソートを作ってみる


Bubble.kt

fun Bubble(b:IntArray){

val len =b.size
//val len =b.lastIndex+1
var lenn : Int
var tmp : Int
if (len == 0){
}else{
for(i in 1..len){
lenn = len - i -1
for (q in 0..lenn){
if(b[q] > b[q+1]){
tmp = b[q]
b[q] = b[q+1]
b[q+1] = xa
}
}
}
}
}


Insertion.kt

fun kihon(d: IntArray) {

var i: Int
var a: Int
var b: Int
i = 1
while (i < d.size) {
val tmp = d[i]
a = 0
while (a < i) {
if (d[a] > tmp) {
break
}
a++
}
b = i
while (b > a) {
d[b] = d[b - 1]
b--
}
d[a] = tmp
i++
}
}


Quick.kt

fun quick_sort(d: IntArray, left: Int, right: Int) {

if (left >= right) {
return
}
val p = d[(left + right) / 2]
var l = left
var r = right
var tmp: Int
while (l <= r) {
while (d[l] < p) {
l++
}
while (d[r] > p) {
r--
}
if (l <= r) {
tmp = d[l]
d[l] = d[r]
d[r] = tmp
l++
r--
}
}
quick_sort(d, left, r)
quick_sort(d, l, right)
}

出力はこっち


main.kt

fun main(args: Array<String>) {

val data = intArrayOf(5, 10, 3, 7, 8, 1, 9)
Bubble(data)
for (i in data.indices) print(data[i].toString() + " ")
}