안드로이드에서 배열 요소를 정렬하는 방법
이 튜토리얼에서는 안드로이드 앱에서 배열 요소를 오름차순으로 정렬하는 방법을 단계별로 살펴봅니다. 자바의 기본 정렬 방식인 교환 정렬(swap 방식)을 직접 구현하여 int형 배열을 정렬하고, 그 결과를 TextView에 출력하는 예제입니다.
1단계 − Android Studio에서 새 프로젝트를 생성합니다. 메뉴에서 File ⇒ New Project를 선택하고, 프로젝트 생성에 필요한 모든 정보를 입력합니다.
2단계 − 아래 코드를 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>
위 레이아웃 코드에는 정렬된 배열 결과를 화면에 표시할 TextView가 하나 포함되어 있습니다. 최상위 LinearLayout은 세로(vertical) 방향으로 배치되며, gravity 속성을 center로 지정해 내용이 화면 중앙에 오도록 설정했습니다.
3단계 − 아래 코드를 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);
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);
}
}
코드 동작 원리
핵심 로직은 이중 for문입니다. 바깥쪽 반복문이 배열의 각 요소를 차례로 가리키면, 안쪽 반복문이 그 뒤에 있는 나머지 요소들과 값을 하나씩 비교합니다. 현재 값보다 작은 값이 발견되면 임시 변수 temp를 이용해 두 요소의 위치를 서로 교환(swap)합니다. 이 과정을 반복하면 비교가 진행될 때마다 가장 작은 값이 앞쪽으로 이동하면서 배열 전체가 오름차순으로 정렬됩니다.
정렬이 완료되면 StringBuffer에 각 요소를 쉼표와 함께 이어 붙여 하나의 문자열로 만든 뒤, setText() 메서드를 통해 TextView에 출력합니다. 동시에 Log.d()를 사용해 Logcat에도 정렬된 값을 기록하므로, 로그 창에서도 결과를 확인할 수 있습니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 기기 선택 목록에서 본인의 모바일 기기를 고르면, 연결된 기기 화면에 아래와 같이 정렬된 배열 결과가 표시됩니다.

실행 결과: 초기 배열 {12, 10, 5, 4, 2, 20, 6, 1, 0, 2}가 다음과 같이 오름차순으로 정렬되어 화면에 나타납니다 → 0 , 1 , 2 , 2 , 4 , 5 , 6 , 10 , 12 , 20