2.1. 수 정렬하기 ¶
#include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { int n, i, j, minj, temp; int *arr; scanf("%d", &n); arr = (int *)malloc(sizeof(int) * n); for(i=0; i<n; i++) scanf("%d", arr + i); for(i=0; i<n; i++) { minj = i; for(j=i+1; j<n; j++) { if(arr[j] < arr[minj]) { minj = j; } } temp = arr[minj]; arr[minj] = arr[i]; arr[i] = temp; printf("%d\n", arr[i]); } return 0; }
2.2. 수 찾기 ¶
#include <stdio.h> #include <stdlib.h> // 오름차순 정렬 int compare (const void *first, const void *second) { if (*(int*)first > *(int*)second) return 1; else if (*(int*)first < *(int*)second) return -1; else return 0; } int main(int argc, char* argv[]) { int n1, n2, i; int *arr1, *arr2; int B_S(int *arr, int size, int solution); scanf("%d", &n1); arr1 = (int *)malloc(sizeof(int) * n1); for(i=0; i<n1; i++) scanf("%d", &arr1[i]); // 정렬 qsort(arr1, n1, sizeof(int), compare); scanf("%d", &n2); arr2 = (int *)malloc(sizeof(int) * n2); for(i=0; i<n2; i++) scanf("%d", &arr2[i]); // 서치 for(i=0; i<n2; i++) { printf("%d\n", B_S(arr1, n1, arr2[i])); } return 0; } // 바이너리 서치 int B_S(int *arr, int size, int solution) { int s=0, e=size-1; int m; while(s <= e) { m = (s+e)/2; if(arr[m] > solution) e = m - 1; else if(arr[m] < solution) s = m + 1; else return 1; } return 0; }
3.1. 수 정렬하기 ¶
#include <stdio.h> int main() { int N; int A[2000]; scanf("%d", &N); for (int i = 0; i < N; i++) { scanf("%d", &A[i]); } for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) { if (A[i] > A[j]) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } } } for (int i = 0; i < N; i++) { printf("%d\n", A[i]); } return 0; }
3.2. 수 찾기 ¶
#include <stdio.h> #include <stdlib.h> int A[100001]; int N; int compare(void *first, void* second){ if(*(int*)first> *(int*)second){ return 1; } else if(*(int*)first<*(int*)second){ return -1; } return 0; } int B_S(int s, int e, int search){ int m = (s+e)/2; if(s>e) return 0; if(A[m]==search) return 1; else if(A[m]>search) return B_S(s,m-1,search); else return B_S(m+1, e, search); } int main() { int i, j, min_idx, tmp, T, search; scanf("%d", &N); for(i=0;i<N;i++) { scanf("%d",&A[i]); } qsort(A, N, sizeof(int), compare); scanf("%d", &T); for(i=0;i<T;i++){ scanf("%d", &search); printf("%d\n", B_S(0, N-1, search)); } return 0; }