quick sort, bouble sort

Dev.Write 2013. 3. 25. 13:20 Posted by zetz
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// 20130322.cpp : Defines the entry point for the console application.
//
 
#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
 
 
template<class Type>
void quick_sort(Type* array, int lower, int upper)
{
    const int mid = (lower + upper) / 2;
    const Type& pivot = array[mid];
    int tlower = lower;
    int tupper = upper;
    while (tlower <= tupper)
    {
        while (array[tlower] < pivot) { ++tlower; }
        while (array[tupper] > pivot) { --tupper; }
         
        if (tlower <= tupper)
        {
            std::swap(array[tlower], array[tupper]);
            --tupper;
            ++tlower;
        }
    }
    if (lower < tupper) { quick_sort(array, lower, tupper); }
    if (tlower < upper) { quick_sort(array, tlower, upper); }
}
 
template<typename T>
void buble_sort(T* array, int N)
{
    int sorted = 0;
    while (!sorted)
    {
        sorted = 1;
        for (int i=0; i< N-1; ++i)
        {
            if (array[i] > array[i+1]) {
                std::swap(array[i], array[i+1]);
                sorted = 0;
            }
        }
    }
}
 
struct seq_generator
{
    seq_generator() : m_number(0) {}
    int operator()() { return m_number++; }
    int m_number;
};
int _tmain(int argc, _TCHAR* argv[])
{
 
    std::vector<char> numberic(10);
    std::generate(numberic.begin(), numberic.end(), seq_generator());
    std::random_shuffle(numberic.begin(), numberic.end());
    std::copy(numberic.begin(), numberic.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout<< std::endl;
 
    std::cout<< "========== sorting =========="<< std::endl;
    quick_sort(&numberic[0], 0, 9);
    //buble_sort(&numberic[0], 10);
     
    std::copy(numberic.begin(), numberic.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout<< std::endl;
    return 0;
}

'Dev.Write' 카테고리의 다른 글

boost::xml_parser wrapper  (1) 2013.06.12
list  (0) 2013.04.12
insert sort, b-search  (0) 2013.03.07
[Python] os 모듈  (0) 2011.10.21
범용적인 fsm 클래스 설계  (0) 2011.10.04