자료구조
자료를 효율적으로 이용할 수 있도록 컴퓨터에 저장하는 방법
배열
같은 자료형의 변수로 이루어진 구성요소(component)가 모인 것
■ 배열의 기본적인 특성
public class IntArray {
public static void main(String[] args) {
int[] array = new int[] {1,2,5,6,9}; //배열 선언 및 초기화
//배열의 각 요소 출력
for (int i=0; i<array.length; i++){
System.out.println("array[" + i + "] = " + array[i]);
}
}
}
■ 배열 요소의 최댓값 구하기
public class MaxOfArray {
public static int maxOf(int[] a){
int max = a[0];
for(int i=1; i<a.length; i++){
if(a[i] > max)
max = a[i];
}
return max;
}
public static void main(String[] args) {
//난수를 사용하여 배열의 요솟값을 설정
Random random = new Random();
int[] a = new int[10];
for(int i=0; i<a.length; i++){
a[i] = random.nextInt(100); //난수의 bound를 설정
}
System.out.println("배열의 최대 값은 : " + maxOf(a));
}
}
■ 배열 요소 역순 정렬
import java.util.Arrays;
import java.util.Random;
public class ReverseArray {
public static void swap(int[] a, int start, int end) {
int temp = a[start];
a[start] = a[end];
a[end] = temp;
}
public static void reverse(int[] a){
for (int i=0; i<a.length/2; i++){
swap(a, i, a.length-i-1);
}
}
public static void main(String[] args) {
int[] a = new int[5];
Random random = new Random();
for (int i=0; i<a.length; i++){
a[i] = random.nextInt(10);
}
System.out.println("배열 : " + Arrays.toString(a));
reverse(a);
System.out.println("배열의 역순 결과 : " + Arrays.toString(a));
}
}
'Algorithm' 카테고리의 다른 글
[기본 자료구조] 링 버퍼[ring buffer] (0) | 2022.01.03 |
---|---|
[기본 자료구조] - 큐 (0) | 2022.01.03 |
기본 자료구조 - 스택[stack] (0) | 2021.12.29 |
검색 알고리즘 - 이진 검색 (0) | 2021.12.29 |
검색 알고리즘 - 선형 검색 (0) | 2021.12.28 |