밍의 기록들😉

[정렬] 선택 정렬, 삽입 정렬, 버블 정렬의 구현 본문

자료구조, 알고리즘/기본다지기

[정렬] 선택 정렬, 삽입 정렬, 버블 정렬의 구현

민쓰 2018. 9. 10. 16:55
선택 정렬 구현 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.Scanner;
 
public class SortSelection { // 선택 정렬
   
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int[] data = new int [100];
     
    for(int i=0; i<n; i++){
      data[i] = sc.nextInt();
    }
    // i : 앞의 정렬이 되어 있는 값들의 다음 위치
    // index : (비교대상 1)으로 최솟값이 담김(i부터 n까지의)
    // j : (비교대상 2) 순차적으로 뒤로 가면서 index와 비교함
    for(int i=0; i<n; i++){
      int index = i;
      for(int j=i+1; j<n; j++){
        if(data[index] > data[j]){ // index값이 j값보다 크다면
          index = j; // index 값이 최솟값이 됨
        }
      }
      int temp;
      temp = data[i];
      data[i] = data[index];
      data[index] = temp;
    }
    for(int i=0; i<n; i++){
      System.out.print(data[i]+" ");
    }
  }
}


삽입 정렬 구현 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.Scanner;
 
public class SortInsertion { //삽입 정렬
 
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int[] data = new int [100];
     
    for(int i=0; i<n; i++){
      data[i] = sc.nextInt();
    }
     
    // i가 가리키고 있는 값이 왼쪽 정렬되어 있는 값과 비교 후 자리에 들어감
    // i : 앞의 정렬되어 있는 값들의 다음 위치 (비교대상 1)
    // j : (비교 대상 2) 순차적으로 앞으로 가면서 i와 비교함
    for(int i=1; i<n; i++){
      for(int j=i; j>=1; j--){
        if(data[j-1] > data[j]){
          int temp;
          temp = data[j-1];
          data[j-1] = data[j];
          data[j] = temp;
        }
        else break;
      }
    }
    for(int i=0; i<n; i++){
      System.out.print(data[i]+" ");
    }
  }
}


버블 정렬 구현 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.Scanner;
 
public class SortBubble { // 버블 정렬
 
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int[] data = new int [100];
     
    for(int i=0; i<n; i++){
      data[i] = sc.nextInt();
    }
     
    // j가 가리키고 있는 값과 오른쪽 값 비교를 n번함
    for(int i=0; i<n; i++){
      for(int j=0; j<n-i-1; j++){
        if(data[j] > data[j+1]){
          int temp;
          temp = data[j];
          data[j] = data[j+1];
          data[j+1] = temp;
        }
      }
    }
    for(int i=0; i<n; i++){
      System.out.print(data[i]+" ");
    }
  }
}


Comments