선택 정렬

2024. 8. 22. 03:28·algorithm

설명

N개이 숫자가 입력되면 오름차순으로 정렬하여 출력하는 프로그램을 작성하세요.

정렬하는 방법은 선택정렬입니다.

 

입력

첫 번째 줄에 자연수 N(1<=N<=100)이 주어집니다.

두 번째 줄에 N개의 자연수가 공백을 사이에 두고 입력됩니다. 각 자연수는 정수형 범위 안에 있습니다.

 

출력

오름차순으로 정렬된 수열을 출력합니다.

 

예시 입력 1 

6
13 5 11 7 23 15

 

예시 출력 1

5 7 11 13 15 23

 

소스코드 1

import java.util.Scanner;

//선택 정렬
public class Main {

    public static void solution(int N, int[] arr) {
        for (int i = 0; i < N - 1; i++) {
            for (int j = i + 1; j < N; j++) {
                if (arr[i] > arr[j]) {
                    int tmp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = tmp;
                }
            }
        }

        //정답
        for (int i : arr) {
            System.out.print(i+" ");
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int arr[] = new int[N];
        for (int i = 0; i < N; i++) {
            arr[i] = sc.nextInt();
        }

        solution(N,arr);
    }
}

 

 

소스 코드 2

import java.util.Scanner;

//선택 정렬2
public class Main {

    public static void solution(int N, int[] arr) {
        for (int i = 0; i < N - 1; i++) { // 0 1 2 3 4
            int idx = i;
            for (int j = i + 1; j < N; j++) { // 1 2 3 4 5 , 2 3 4 5 , 3 4 5, 4 5, 5
                if (arr[idx] > arr[j]) {
                    idx = j;
                }
            }

            int tmp = arr[i];
            arr[i] = arr[idx];
            arr[idx] = tmp;
        }

        //정답
        for (int i : arr) {
            System.out.print(i+" ");
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int arr[] = new int[N];
        for (int i = 0; i < N; i++) {
            arr[i] = sc.nextInt();
        }

        solution(N,arr);
    }
}

'algorithm' 카테고리의 다른 글

LRU  (0) 2024.08.24
버블 정렬  (0) 2024.08.22
씨름 선수  (0) 2024.06.06
Comparable<T> 인터페이스  (0) 2024.06.06
응급실  (0) 2024.06.05
'algorithm' 카테고리의 다른 글
  • LRU
  • 버블 정렬
  • 씨름 선수
  • Comparable<T> 인터페이스
juuuuuuun
juuuuuuun
  • juuuuuuun
    namae
    juuuuuuun
  • 전체
    오늘
    어제
    • 분류 전체보기 (94)
      • java (2)
      • Infra (4)
      • server (2)
      • algorithm (52)
      • HTTP (8)
      • android (1)
      • baekjoon (16)
      • 소프트웨어공학 (6)
      • 기타 (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
juuuuuuun
선택 정렬
상단으로

티스토리툴바