알고리즘/알고리즘 코드

[C언어] 퀵정렬 (Quick Sort) 소스 코드

ahdelron 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; *= *b; *= temp;
}
 
// 퀵소트 함수 
void quickSort(int arr[], int start, int end)
{
    // 종료 조건 
    if(start >= endreturn;
    
    // 피벗 (왼쪽 고정)
    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 + 1end);
}
 
int main(void)
{
    int arr[10= { 21431078695 };
    
    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