본문 바로가기

전체 글

[C code] 계수 정렬 (Counting Sort) 첫번째 방법 - 기존의 Array 정렬 #include #include // Function to sort an array using counting sort void CountingSort(int arr[], int n) { //in arr, max value == max == counting_arr max index int max = 0 , i; for(i=0 ; i max) max = arr[i]; } int output_arr[n]; int counting_arr[max]; for(i=0 ; i output_arr[6] = 5; (후에 output_arr[6]--;) ... arr[0]의 값인 1 -> counting_arr[1]의 값인 0 -> output_arr[0] = 1; ​ -Geeksf.. 더보기
[C code] 삽입 정렬 (Insertion sort) #include #include // Function to sort an array using insertion sort void InsertionSort(int arr[], int n) { int key, i, j; for(i=0 ; i=0 && arr[j]>key) { arr[j+1] = arr[j]; j--; } arr[j+1] = key; } } /* Function to print an array */ void PrintArray(int arr[], int size) { printf("\n**********************\n"); for(int i=0 ; i 더보기
[C code] 버블 정렬 (Bubble sort) #include #include void Swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } // A function to implement bubble sort void BubbleSort(int arr[], int n) { int i, j; for (i = n-1 ; i > 0 ; i--) // arr[n-1] ~ arr[1] put bigger number { for (j = 0 ; j arr[j+1]) Swap(&arr[j], &arr[j+1]); } } } /* Function to print an array */ void PrintArray.. 더보기
[C code] 입력버퍼 비우기 scanf(), fgets(,,) 함수로 여러 문자열을 입력받다보면, 중간에 엔터키(\n)가 입력버퍼에 남아 입력하지도 않고도 입력이 되는 상황이 나타난다 (다음 함수 호출 시에 버퍼에 남아있는 '\n'가 입력됨) ​ fgets(char * s, int n, FILE * stream) 함수같은 경우에는, n값 안에 '\0'값도 포함되어 실제적으로 n-1개의 문자를 입력받을 수 있는데, 이를 넘어서 입력하게 되면 엔터키(\n)가 저절로 입력버퍼에 남게 된다 ​ 이를 해결하기 위해서는, 입력함수 후에 void ClearLineFromReadBuffer(void) { while(getchar() != '\n'); } ClearLineFromReadBuffer() 함수를 호출하는 것 ! 물론 이 이외에도 ​ 1.. 더보기
[C code] Boolean 자료형 #include #include #include void Judg(_Bool flag) { printf("%d - %s\n", flag, flag ? "true" : "false"); } int main() { Judg(1); Judg(5 < 4); Judg(1 == 3-2); Judg(true); Judg(false); return 0; } Output : 1 - true 0 - false 1 - true 1 - true 0 - false 선언할 때에 선언 후 bool f; 라고만 해도 좋지만, c언어는 기본적으로 bool을 자동으로 지원하지 않기에 _Bool f; 로 선언할 수도 있음 ​ 또, true와 false 등을 사용하려면 stdbool.h의 헤더파일을 사용해야 함 (Visual Studio는.. 더보기