Tugas3-SelectionSort/MainActivity.kt
2025-10-31 15:00:33 +07:00

98 lines
3.1 KiB
Kotlin
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.example.selectionsort
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.selectionsort.ui.theme.SelectionSortTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
SelectionSortTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
SelectionSortScreen(modifier = Modifier.padding(innerPadding))
}
}
}
}
}
@Composable
fun SelectionSortScreen(modifier: Modifier = Modifier) {
// Daftar angka acak 10 elemen antara 1099
val numbers = remember { (10..99).shuffled().take(10) }
// Proses Selection Sort
val sortedNumbers = remember {
numbers.toMutableList().apply {
for (i in 0 until size - 1) {
var minIndex = i
for (j in i + 1 until size) {
if (this[j] < this[minIndex]) {
minIndex = j
}
}
if (minIndex != i) {
val temp = this[i]
this[i] = this[minIndex]
this[minIndex] = temp
}
}
}
}
Column(
modifier = modifier
.padding(16.dp)
.verticalScroll(rememberScrollState())
) {
Text(
text = "🔢 Daftar Angka Sebelum Diurutkan:",
style = MaterialTheme.typography.titleMedium
)
Text(text = numbers.joinToString(", "))
Text(text = "")
Text(
text = "✅ Hasil Setelah Diurutkan (Selection Sort):",
style = MaterialTheme.typography.titleMedium
)
Text(text = sortedNumbers.joinToString(", "))
Text(text = "")
Text(
text = "🧠 Cara Kerja Selection Sort:",
style = MaterialTheme.typography.titleMedium
)
Text(
text = "Algoritma ini mencari nilai terkecil dari bagian data yang belum diurutkan, " +
"lalu menukarnya dengan posisi paling depan. Langkah ini diulang terus " +
"hingga seluruh data terurut dari yang terkecil ke terbesar."
)
}
}
@Preview(showBackground = true)
@Composable
fun SelectionSortScreenPreview() {
SelectionSortTheme {
SelectionSortScreen()
}
}