구현 - 버블정렬, 선택 정렬, 삽입 정렬, 셸 정렬
2018. 3. 14. 01:21
이제 문제는 n log n 정렬들이군..
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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | #include <iostream> #include <ctime> using namespace std; constexpr int arrSize =40000; void bubble(int* arr, int size) { cout << "Bubble Sort " << endl; for (int i = size - 1; i >= 0; --i) for (int j = 0; j < i; ++j) if (arr[j] > arr[j + 1]) swap(arr[j], arr[j + 1]); } void selection(int* arr, int size) { cout << "Selection Sort " << endl; for (int i = 0; i < size - 1; ++i) { int leastIdx = i; for (int j = i + 1; j < size; ++j) if (arr[j] < arr[leastIdx]) leastIdx = j; swap(arr[i], arr[leastIdx]); } } void insertion(int* arr, int size) { cout << "Insertion Sort " << endl; for (int i = 1; i < size; ++i) { int saved = arr[i]; int j = i - 1; for ( ; j >= 0 && saved < arr[j]; --j) arr[j + 1] = arr[j]; arr[j + 1] = saved; } } void shell(int* arr, int size) { cout << "Shell Sort" << endl; for (int gap = size / 2; gap >0; gap /= 2) { if (gap % 2 == 0) ++gap; for (int i = gap; i < size; i += gap) { int j = i - gap; int saved = arr[i]; for ( ; j >= 0 && saved < arr[j]; j -= gap) arr[j + gap] = arr[j]; arr[j + gap] = saved; } } } void testSort(void(*sortFunc)(int*, int)) { int arr[arrSize]; cout << "size of n " << arrSize << endl; for (int i = 0; i < arrSize; ++i) arr[i] = rand() % 99; clock_t start, finish; double duration; start = clock(); sortFunc(arr, arrSize); finish = clock(); duration = (double)(finish - start) / CLOCKS_PER_SEC; cout << "duration : " << duration << endl; if(arrSize < 100) for (int& a : arr) cout << a << " "; cout << endl << endl; } int main() { srand(size_t(time(nullptr))); testSort(bubble); testSort(selection); testSort(insertion); testSort(shell); return 0; } |
'프로그래밍' 카테고리의 다른 글
03/26 자료구조들 (0) | 2018.03.26 |
---|---|
구현 - 병합 정렬, 퀵 정렬, 기수 정렬 (0) | 2018.03.14 |
구현 - 다익스트라 dijkstra, 플로이드 floyd (0) | 2018.03.12 |
구현 - 프림 알고리즘 (0) | 2018.03.12 |
구현 - 가중치 그래프와 크루스칼 알고리즘 (0) | 2018.03.11 |