การจัดเรียงลำดับข้อมูลในอาร์เรย์บน Android
ตัวอย่างนี้สาธิตวิธีเรียงลำดับตัวเลขในอาร์เรย์แบบกำหนดเอง (Manual Sorting) และแสดงผลใน TextView
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → File → New Project → ตั้งค่าโปรเจกต์
ขั้นตอนที่ 2: Layout XML (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
ขั้นตอนที่ 3: โค้ด Java (src/MainActivity.java)
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
TextView text;
int temp;
int[] arr = {12, 10, 5, 4, 2, 20, 6, 1, 0, 2};
ArrayList<String> arrayList;
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
// เรียงลำดับแบบ Bubble Sort (สำหรับการศึกษา)
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
// สร้างข้อความแสดงผล
StringBuffer buff = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
buff.append(String.valueOf(arr[i] + " , "));
Log.d("sai", String.valueOf(arr[i]));
}
text.setText(buff);
}
}
วิธีที่ดีกว่า: ใช้ Arrays.sort()
ในการพัฒนาจริง ควรใช้เมธอดสำเร็จรูปของ Java:
// เรียงจากน้อยไปมาก Arrays.sort(arr); // เรียงจากมากไปน้อย (ต้องแปลงเป็น Integer[] ก่อน) Integer[] arrObj = Arrays.stream(arr).boxed().toArray(Integer[]::new); Arrays.sort(arrObj, Collections.reverseOrder());
การทดสอบ
รันแอป จะแสดงตัวเลขเรียงจากน้อยไปมาก: 0, 1, 2, 2, 4, 5, 6, 10, 12, 20

สรุป
- ตัวอย่างใช้ Bubble Sort เพื่อเข้าใจหลักการทำงาน
- ใน Production ให้ใช้
Arrays.sort()หรือCollections.sort()ซึ่งมีประสิทธิภาพดีกว่า (O(n log n)) - สำหรับ String ใช้
Arrays.sort(stringArray)จะเรียงตามตัวอักษร