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 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | #include <cstdio> #include <cstdlib> #include <random> #include <chrono> #include <algorithm> #include <cstring> using namespace std; template <typename Type> void Insertion_Sort(Type *_array, int _n) { // 0th index가 정렬되었다고 가정 for (int i = 1; i < _n; i++) { // 1th index부터 탐색 for (int j = i; j > 0; j--) { if (_array[j - 1] > _array[j]) { swap(_array[j - 1], _array[j]); } else { break; } } } } template <typename Type> void Insertion_Sort_without_Swap(Type *_array, int _n) { for (int i = 1; i < _n; i++) { Type temp = _array[i]; for (int j = i; j > 0; j--) { if (_array[j - 1] > temp) { _array[j] = _array[j - 1]; } else { _array[j] = temp; break; } } //오른쪽으로 다 밀고 맨 왼쪽 값이 key 값보다 크다면! if (_array[0] > temp) { _array[0] = temp; } } } template <typename Type> bool Is_Sorted(Type *_array, int _n) { //정렬이 잘 되었는지 check for (int i = 1; i < _n; i++) { if (_array[i - 1] > _array[i]) { return false; } } return true; } int main(int argc, char **argv) { // Get random number random_device rd; default_random_engine gen(rd()); uniform_int_distribution<int> dist(0, 10 * 1000 * 1000); int n = atoi(argv[1]); int *data = new int[n]; printf("Data : \n"); for (int i = 0; i < n; i++) { data[i] = dist(gen); //printf("10%d\n", data[i]); } // Set start time chrono::time_point<chrono::system_clock> startTime = chrono::system_clock::now(); if (strcmp(argv[2], "insertion") == 0) { Insertion_Sort<int>(data, n); } else if (strcmp(argv[2], "insertion_without_swap") == 0) { Insertion_Sort_without_Swap<int>(data, n); } else if (strcmp(argv[2], "std") == 0) { // STL function // 시작, 끝 주소 인자 sort(&(data[0]), &(data[n])); } else { // do something } printf("Sorted : \n"); //for (int i = 0; i < n; i++) { // printf("10%d\n", data[i]); //} // Set end time chrono::time_point<chrono::system_clock> endTime = chrono::system_clock::now(); chrono::milliseconds timeDiff = chrono::duration_cast<chrono::milliseconds>(endTime - startTime); double T = timeDiff.count(); printf("Runtime = %d ms\n", (int)T); bool flag = Is_Sorted<int>(data, n); if (flag) { printf("Correct\n"); } else { printf("Wrong\n"); } return 1; } | cs |
'[알고리즘개론] - Algorithm > [Concept]' 카테고리의 다른 글
알고리즘 Find_Max (0) | 2020.10.20 |
---|---|
시간측정 (0) | 2020.10.17 |
알고리즘 Part 4 (0) | 2020.10.05 |
알고리즘 Part 3 (0) | 2020.10.05 |
알고리즘 Part 1 (0) | 2020.10.05 |