[C언어] 퀵정렬 (Quick Sort) 소스 코드
2020. 4. 12. 21:01ㆍ알고리즘/알고리즘 코드
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | #include <stdio.h> #define SIZE 10 // 양쪽 값 변경 inline void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } // 퀵소트 함수 void quickSort(int arr[], int start, int end) { // 종료 조건 if(start >= end) return; // 피벗 (왼쪽 고정) int nPivot = arr[start]; int i = start, j = end; while(i < j) { // 피벗보다 작은 숫자를 찾아야 돼서 j가 먼저 감소 while(nPivot < arr[j]) j--; while(i < j && nPivot >= arr[i]) i++; swap(arr + i, arr + j); } swap(arr + start, arr + j); quickSort(arr, start, j - 1); quickSort(arr, j + 1, end); } int main(void) { int arr[10] = { 2, 1, 4, 3, 10, 7, 8, 6, 9, 5 }; printf("정렬 전 : "); for(int i = 0; i < SIZE; i++) { printf("%d ", arr[i]); } printf("\n"); quickSort(arr, 0, SIZE - 1); printf("정렬 후 : "); for(int i = 0; i < SIZE; i++) { printf("%d ", arr[i]); } return 0; } | cs |
Output:
정렬 전 : 2 1 4 3 10 7 8 6 9 5
정렬 후 : 1 2 3 4 5 6 7 8 9 10
'알고리즘 > 알고리즘 코드' 카테고리의 다른 글
[C언어] 병합정렬 (Merge Sort) 소스 코드 (0) | 2020.04.12 |
---|---|
[C언어] 에라토스테네스의 체 함수 (0) | 2020.04.11 |