Last active
December 12, 2017 08:22
-
-
Save fpdjsns/deaa97a92b2a76cb486f3dfc95350310 to your computer and use it in GitHub Desktop.
삽입 정렬. 입력 : 숫자 개수(n), n개의 숫자. 출력 : 오름차순으로 정렬된 배열
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#define SIZE 1000 | |
using namespace std; | |
int main() | |
{ | |
int n; | |
int arr[SIZE]; | |
//입력 | |
cin >> n; | |
for (int i = 0; i < n; i++) | |
cin >> arr[i]; | |
//i번째 원소 정렬 | |
for (int i = 0; i < n; i++) | |
{ | |
int now = arr[i]; | |
int j = i - 1; | |
for (; j >= 0; j--) | |
{ | |
//현재 삽입하려는 수(now) 보다 arr[j]가 큰 경우 | |
//now는 앞으로 더 가야됨 | |
if (arr[j] > now) | |
arr[j + 1] = arr[j];//j번째 수를 뒤로 한 칸 옮긴다. | |
//현재 삽입하려는 수(now) 보다 arr[j]가 작거나 같은 경우 | |
//now는 앞으로 더 갈 필요 없음. j번째 뒤가 now의 정렬된 자리임 | |
else | |
break;//반복문 종료 | |
} | |
//j번째 뒤에 now를 넣어줌 | |
arr[j + 1] = now; | |
} | |
//출력 | |
for (int i = 0; i < n; i++) | |
printf("%d ",arr[i]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment