2015년 2월 12일 목요일

[Algorithm] Quick Sort

Quick Sort는 보편적으로 가장 빠른 정렬 알고리즘으로 pivot값을 정할때 전체 값중 한쪽에 편중된 pivot이 정해지면 효율이 최악이 될 수도 있어, 경우에 따라서는 Counting Sort가 빠른 경우도 있다.

또한 정렬할 배열이 100개 이하라면 선택 정렬을 사용하는게 속도에 유리할 수가 있다.



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
void quicksort(int arr[], int left, int right){
    int i = left, j = right;
    int tmp;
    int pivot = arr[(left + right) / 2];
    while (i <= j){
        while (arr[i] < pivot)
            i++;
        while (arr[j] > pivot)
            j--;
        if (i <= j){
            tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
            i++;
            j--;
        }
    }
    if (left < j)
        quicksort(arr, left, j);
    if (i < right)
        quicksort(arr, i, right);
}
cs

[Basic Skill] 2,4,8,16진수 -> 10진수 변환하기

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
// 제곱근
int power(int value, int num){
    int result = 1;
    for (int i = 0; i < num; i++)
        result *= value;
    return result;
}
// 진수변환하기 (2,4,8,16 진수를 10진수로 변환)
// input ex) B, Q, O, H  (순서대로, 2, 4, 8, 16진수)
// 2진수 양수 )  1.0.1.1.B  or  +1.1.0.B
// 4진수 음수 )  -3.0.1.1.Q
// 16진수 음수 )  -A.9.F.H
int converToDec(char * str, int length, int type){
    int count = 0;
    // 해당 진수의 재곱근하여 자리수를 찾음.
    count = power(type, (length + 1/ 2 -1);
    int result = 0;
    char tempStr[50= { 0, };
    int start = 0;
    int end = 0;
    bool minus = false;
    int atoi = 0;
    
    for (int i = 0; i <= length; i++){
        if (*(str + i) == '.'){
            end = i;
            stringCopy(tempStr, str, start, end);
            atoi = asciiToInteger(tempStr);
            result += atoi * count;
            start = end + 1;
            count /= type;            
        }
        else if (*(str + i) == '-'){ // 음수일경우
            start = i + 1;
            minus = true;
        }
        else if (*(str + i) == '+'){ // 양수일경우
            start = i + 1;
        }
    }
    if (minus)
        return -result;
    return result;
}
cs