본문 바로가기
  • Let's study
알고리즘/C++

[알고리즘] 버블 정렬 - C++

by 코딩고수이고파 2021. 9. 22.

버블 정렬


#include <iostream>

using namespace std;

int arr[] = {4, 2, 6, 1, 5, 3};

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL), cout.tie(NULL);
    
    for (int i = 0; i < 5; i++){
        for (int j = 0; j < 5 - i; j++){
            if (arr[j] > arr[j + 1]){	//붙어있는 두 값을 비교하여 왼쪽보다 오른쪽이 작을 경우
                int temp = arr[j];	//자리 바꿈
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    
    for (int i=0; i < 6; i++)
        cout << arr[i] << ' ';
        
    return 0;
}

시간 복잡도: O(N^2)

'알고리즘 > C++' 카테고리의 다른 글

[알고리즘] 삽입 정렬 - C++  (0) 2021.09.22
[알고리즘] 선택 정렬 - C++  (0) 2021.09.22
[알고리즘] Algorithm 헤더 - C++  (0) 2021.09.19
[알고리즘] C++ Vector 사용법  (0) 2021.09.09
[알고리즘] C++ 기본  (0) 2021.09.09

댓글