O operator()(I begin, SI end, O out_begin, SO out_end, C pred_ = C{}, PI in_proj_ = PI{}, PO out_proj_ = PO{}) const { auto && pred = invokable(pred_); auto && in_proj = invokable(in_proj_); auto && out_proj = invokable(out_proj_); O r = out_begin; if(r != out_end) { for(; begin != end && r != out_end; ++begin, ++r) *r = *begin; make_heap(out_begin, r, std::ref(pred), std::ref(out_proj)); auto len = r - out_begin; for(; begin != end; ++begin) { if(pred(in_proj(*begin), out_proj(*out_begin))) { *out_begin = *begin; detail::sift_down_n(out_begin, len, out_begin, std::ref(pred), std::ref(out_proj)); } } sort_heap(out_begin, r, std::ref(pred), std::ref(out_proj)); } return r; }
void practice_heap() { std::vector<int> v { 3, 1, 4, 1, 5, 9 }; std::cout << "initially, v: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; std::make_heap(v.begin(), v.end()); std::cout << "after make_heap, v: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; std::pop_heap(v.begin(), v.end()); auto largest = v.back(); v.pop_back(); std::cout << "largest element: " << largest << '\n'; std::cout << "after removing the largest element, v: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; cout << "after sort_heap: " << endl; sort_heap(v.begin(), v.end()); for (auto i : v) cout << i << " "; cout << endl; }
// Pickup a passenger. void Elevator::pickup(vector<int> passengers, int presentFloor, int direction) { // Let everyone alight from the lift at the start. // So people for current floor is equal to 0. int count = destFloors.size(); if (destFloors[0] == presentFloor && count != 0) { peoplePerFloor[presentFloor] = 0; destFloors.erase(destFloors.begin()); } // Let people waiting the on floor to get in if (direction == UP) { for (auto &it : passengers) { auto exists = find(destFloors.begin(), destFloors.end(), it); if (exists != destFloors.end()) { peoplePerFloor[it] += 1; } else { destFloors.push_back(it); make_heap(destFloors.begin(), destFloors.end()); peoplePerFloor[it] = 1; } } sort_heap(this->destFloors.begin(), this->destFloors.end()); } else if (direction == DOWN) { for (auto &it : passengers) { auto exists = find(destFloors.begin(), destFloors.end(), it); if (exists != destFloors.end()) { peoplePerFloor[it] += 1; } else { destFloors.push_back(it); make_heap(destFloors.begin(), destFloors.end()); peoplePerFloor[it] = 1; } } sort_heap(destFloors.begin(), destFloors.end()); reverse(destFloors.begin(), destFloors.end()); } else { for (auto &it : passengers) { destFloors.push_back(1); peoplePerFloor[it] = 1; } make_heap(destFloors.begin(), destFloors.end()); this->direction = direction; if (direction == DOWN) reverse(destFloors.begin(), destFloors.end()); } for (auto &it : this->destFloors) cout << it << endl; }
int main() { int arr[] = {6, 5, 3, 1, 8, 7, 2, 4}; int len = sizeof(arr)/sizeof(int); array_display(arr, len); sort_heap(arr, len); array_display(arr, len); }
void TestHeapOperations (void) { static const int c_Values [31] = { // 31 values make a full 4-layer tree 93, 92, 90, 86, 83, 86, 77, 40, 72, 36, 68, 82, 62, 67, 63, 15, 26, 26, 49, 21, 11, 62, 67, 27, 29, 30, 35, 23, 59, 35, 29 }; vector<int> v; v.reserve (VectorSize(c_Values)); for (uoff_t i = 0; i < VectorSize(c_Values); ++ i) { v.push_back (c_Values[i]); push_heap (v.begin(), v.end()); cout << "------------------------------------------------\n"; if (!is_heap (v.begin(), v.end())) cout << "Is NOT a heap\n"; PrintHeap (v); } cout << "------------------------------------------------\n"; cout << "make_heap on the full range:\n"; v.resize (VectorSize (c_Values)); copy (VectorRange(c_Values), v.begin()); make_heap (v.begin(), v.end()); PrintHeap (v); if (!is_heap (v.begin(), v.end())) cout << "Is NOT a heap\n"; cout << "------------------------------------------------\n"; cout << "pop_heap:\n"; pop_heap (v.begin(), v.end()); v.pop_back(); PrintHeap (v); if (!is_heap (v.begin(), v.end())) cout << "Is NOT a heap\n"; cout << "------------------------------------------------\n"; cout << "sort_heap:\n"; v.resize (VectorSize (c_Values)); copy (VectorRange(c_Values), v.begin()); make_heap (v.begin(), v.end()); sort_heap (v.begin(), v.end()); foreach (vector<int>::const_iterator, i, v) cout << *i; cout << endl; cout << "------------------------------------------------\n"; cout << "priority_queue push and pop:\n"; priority_queue<int> q; for (uoff_t i = 0; i < VectorSize(c_Values); ++ i) q.push (c_Values[i]); while (!q.empty()) { cout << q.top(); q.pop(); } cout << endl; }
void heap_algo(){ cout<<endl<<"set_algo :"<<endl; int ia1[9] = {0, 1, 2, 3, 4, 8, 9 , 3 , 5 }; vector<int> ivec(ia1,ia1+9); make_heap(ivec.begin(),ivec.end(),greater<int>()); //默认最大堆,这样就是最小堆 cout<<ivec<<endl; ivec.push_back(7); push_heap(ivec.begin(),ivec.end(),greater<int>()); //对新加入的元素调整位置 cout<<ivec<<endl; pop_heap(ivec.begin(),ivec.end(),greater<int>()); //堆首删除放到容器尾 ivec.pop_back(); cout<<ivec<<endl; sort_heap(ivec.begin(),ivec.end(),greater<int>()); //堆排序 cout<<ivec<<endl; }
std::vector<long> listDegrees(const Graph & g) { std::vector<long> list(order(g), 0); typedef typename boost::graph_traits<Graph>::edge_iterator eiter; std::pair<eiter, eiter> ep; for (ep = edges(g); ep.first != ep.second; ++ep.first) { int u = source(*ep.first,g), v = target(*ep.first,g); list[u]++; list[v]++; } make_heap(list.begin(), list.end()); sort_heap(list.begin(), list.end()); return list; }
void ga_k_means_clustering::updateScores() { //for the GA first for(int i=0; i<GAPOPULATIONSIZE; i++) { ga.setScores(NUMBEROFCLUSTERS*NUMBEROFPOINTSPERCLUSTER, points); } //now for the KMeans if(k_means_clusters.size()!=0) { for(int i=0; i<KMEANSPOPULATIONSIZE; i++) k_means_clusters[i].setScore(NUMBEROFCLUSTERS*NUMBEROFPOINTSPERCLUSTER, points); make_heap(k_means_clusters.begin(),k_means_clusters.end()); sort_heap(k_means_clusters.begin(),k_means_clusters.end()); } }
I operator()(I begin, I middle, S end, C pred_ = C{}, P proj_ = P{}) const { auto && pred = invokable(pred_); auto && proj = invokable(proj_); make_heap(begin, middle, std::ref(pred), std::ref(proj)); auto const len = middle - begin; I i = middle; for(; i != end; ++i) { if(pred(proj(*i), proj(*begin))) { iter_swap(i, begin); detail::sift_down_n(begin, len, begin, std::ref(pred), std::ref(proj)); } } sort_heap(begin, middle, std::ref(pred), std::ref(proj)); return i; }
void LanguageModel::prune_level(uint32_t lvl, size_t cut_num) { assert(lvl >= 1 && "cannot prune unigram"); cerr << "[PRUNING][ORDER=" << (lvl + 1) << "] cut_num = " << cut_num << endl; cerr << "[PRUNING][ORDER=" << (lvl + 1) << "] calculate entropy distance..." << endl; size_t num_in_level = used_ngram_num_per_order[lvl]; if (cut_num > num_in_level) { cut_num = num_in_level; } size_t total_num_in_level = ngram_num_per_order[lvl]; GramInfo *node_info_buff = new GramInfo[num_in_level]; size_t buff_idx = 0; //当前有多少可供裁剪的gram for (size_t i = 0; i < total_num_in_level; i++) { GramNode &n = grams_per_order[lvl][i]; if (mask_for_grams[n.gram_id] & DONT_PRUNE) { continue; } if (prob_buff[n.gram_id] > 2.0) { //这个概率是invalid的,代表这个gram已经被删除 continue; } if (n.gram_id < low_gram_num && child_num_buff[n.gram_id] != 0) { //有更高阶的gram依赖这个gram,因此不能删除 continue; } GramInfo &info = node_info_buff[buff_idx++]; info.node = &n; info.dis = calc_distance(lvl, &n); } cerr << "[PRUNING][ORDER=" << (lvl + 1) << "] gram_num_can_be_removed = "<< buff_idx <<", sorting..." << endl; make_heap(node_info_buff, node_info_buff + buff_idx); sort_heap(node_info_buff, node_info_buff + buff_idx); size_t cutted = 0; for (size_t i = 0; i < buff_idx && cutted < cut_num; i++) { //将这些熵的增量小的都可以删除 cutted++; GramNode *node = node_info_buff[i].node; prob_buff[node->gram_id] = 3.0; //用不合法的prob来标记当前的node被删除 mask_for_grams[node->prefix->gram_id] |= PRUNED; used_ngram_num_per_order[lvl]--; child_num_buff[node->prefix->gram_id]--; } delete[] node_info_buff; cerr << "[PRUNING][ORDER=" << (lvl + 1) << "] finished." << endl; }
std::vector<long> listEccentricities(const Graph & g) { dMatrix dist = distanceMatrix(g); long n = order(g); std::vector<long> res(n); for (long i = 0; i < n; i++) { long m = 0; for (long j = 0; j < n; j++) { if (m < dist[i][j]) { m = dist[i][j]; } } res[i] = m; } make_heap(res.begin(), res.end()); sort_heap(res.begin(), res.end()); return res; }
// E.g.: called by manage_buffer in Optimizer in case of a new upper bound // on the objective ("loup"). This function then removes (and deletes) from // the heap all the cells with a cost greater than loup. void CellHeap::contract_heap(double loup) { //cout << " before contract heap " << l.size() << endl; sort_heap(l.begin(),l.end(),CellComparator()); vector<pair<Cell*,double> >::iterator it0=l.begin(); int k=0; while (it0!=l.end() && it0->second > loup) { it0++; k++; } for (int i=0;i<k;i++) { delete l[i].first; } if (k>0) l.erase(l.begin(),it0); make_heap(l.begin(), l.end() ,CellComparator()); //cout << " after contract heap " << l.size() << endl; }
O operator()(I begin, SI end, O out_begin, SO out_end, C pred = C{}, PI in_proj = PI{}, PO out_proj = PO{}) const { O r = out_begin; if(r != out_end) { for(; begin != end && r != out_end; ++begin, ++r) *r = *begin; make_heap(out_begin, r, std::ref(pred), std::ref(out_proj)); auto len = r - out_begin; for(; begin != end; ++begin) { auto &&x = *begin; if(invoke(pred, invoke(in_proj, x), invoke(out_proj, *out_begin))) { *out_begin = (decltype(x) &&) x; detail::sift_down_n(out_begin, len, out_begin, std::ref(pred), std::ref(out_proj)); } } sort_heap(out_begin, r, std::ref(pred), std::ref(out_proj)); } return r; }
maina() { int i = 0; int *task_array; int selected_sort = 1, selected_array = 1, selected_size = 1, size_of_array = 0, rand_min = 0, rand_max = 100; int command; int *array_selected = 0; bool recalled = FALSE; long double *ld_array, sum, variance, avg; setlocale(LC_ALL, "Korean"); { printf("\t정렬 알고리즘 정밀 측정기\n\n"); RE_COLE1: printf("\t알고리즘 선택\n\t1. 선택\t\t2. 삽입\t3. 거품\t4. 쉘\t5. 퀵\t6. 퀵(비재귀)\n\t7. 퀵(랜덤)\t8. 퀵(부분)\t9. 퀵(가운데)\n" "\t10. 기수\t11. 버킷\t12. 힙\t13. 병합\n\t14. 자동생성\n선택 : "); scanf_s("%d", &selected_sort); if (selected_sort < 1 || selected_sort > 14) { printf("다시 선택하세요.\n"); goto RE_COLE1; } else if (selected_sort == 14) { printf("\n\t오류가 심한 버킷알고리즘은 제외하고 생성합니다.\n\t시작하려면 아무키나 눌러주세요..."); _getch(); printf("\n"); report_auto(); } if (recalled) goto RECALLED; RE_COLE2: printf("\n\t배열 선택\n\t1. 순배열\t2. 역순배열\t3. 중복없는 임의배열\n\t4. 중복있는 임의배열\n선택 : "); scanf_s("%d", &selected_array); if (selected_array < 1 || selected_array > 4) { printf("다시 선택하세요.\n"); goto RE_COLE2; } if (selected_array > 2) { RE_SET1: printf("랜덤최소 숫자 : "); scanf_s("%d", &rand_min); printf("랜덤최고 숫자 : "); scanf_s("%d", &rand_max); if (rand_min >= rand_max || rand_min < 0) { printf("다시 맞춰라\n"); goto RE_SET1; } } if (recalled) goto RECALLED; RE_COLE3: printf("\n\t배열 크기 선택\n\t1. 10\t2. 100\t3. 1,000\t4. 10,000\t5. 100,000\n\t6. 1,000,000\t7. 직접입력\n선택 : "); scanf_s("%d", &selected_size); if (selected_size < 1 || selected_size > 7) { printf("다시 선택하세요.\n"); goto RE_COLE3; } if (selected_size == 7) { printf("횟수 입력 : "); scanf_s("%d", &size_of_array); } else size_of_array = pow(10, selected_size); if (recalled) goto RECALLED; } recalled = TRUE; { RECALLED: fast_cls(); while (TRUE) { wprintf(L"\t선택된 알고리즘: %s\n\t선택된 배 열: %s\n\t선택된 배열크기: %s\n", sort_name[selected_sort - 1], array_name[selected_array - 1], commasput(size_of_array)); if (selected_array > 2) { printf("\t숫 자 범 위: %d ~ %d", rand_min, rand_max); } printf("\n\n"); printf("\t1. 알고리즘변경\t\t2. 배열변경\t3. 크기변경"); if (selected_array > 2) { printf("\t4. 범위변경\n\t5. 실험시작"); } else printf("\t4. 실험시작"); printf("\n>> "); scanf_s("%d", &command); if (selected_array > 2 && command == 4) goto RE_SET1; else if (command == 1) goto RE_COLE1; else if (command == 2) goto RE_COLE2; else if (command == 3) goto RE_COLE3; else if (command == 4 || (selected_array > 2 && command == 5)) { RAND_MIN = rand_min; RAND_SECTION = rand_max - rand_min + 1; SIZE_OF_ARRAY = size_of_array; array_direct = (int *)malloc(sizeof(int)*size_of_array); array_reverse = (int *)malloc(sizeof(int)*size_of_array); array_random = (int *)malloc(sizeof(int)*size_of_array); array_overlap = (int *)malloc(sizeof(int)*size_of_array); fast_cls(); printf("진행횟수? "); scanf_s("%d", &command); fast_cls(); selected_array_g = selected_array; task_array = (int *)malloc(sizeof(int) * SIZE_OF_ARRAY); ld_array = (long double *)malloc(sizeof(long double) * command); for (i = 0; i < command; i++) { init_array(); if (selected_array == 1) array_selected = array_direct; else if (selected_array == 2) array_selected = array_reverse; else if (selected_array == 3) array_selected = array_random; else if (selected_array == 4) array_selected = array_overlap; switch (selected_sort) { case 1: timer_start(); sort_selection (array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 2: timer_start(); sort_insertion (array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 3: timer_start(); sort_bubble (array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 4: timer_start(); sort_shell (array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 5: timer_start(); sort_quick0 (array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 6: timer_start(); sort_quick1 (array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 7: timer_start(); sort_quick2 (array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 8: timer_start(); sort_quick3 (array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 9: timer_start(); sort_quick4 (array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 10: timer_start(); radix_sort (array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 11: timer_start(); sort_bucket (array_selected, SIZE_OF_ARRAY, task_array); timer_finish(); break; case 12: timer_start(); sort_heap (array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 13: timer_start(); sort_merge (array_selected, SIZE_OF_ARRAY, task_array); timer_finish(); break; } ld_array[i] = timer_getns(); } free(task_array); printf("\n\n--------------실험 결과--------------\n"); sum = 0.0f; for (i = 0; i < command; i++) { printf("%.12lf ns\n", ld_array[i]); sum += ld_array[i]; } avg = sum / command; variance = 0.0f; for (i = 0; i < command; i++) { variance += pow(ld_array[i] - avg, 2); } variance /= command; printf("-------------------------------------\n"); printf("합계 : %.12lf ns\n평균 : %.12lf ns\n분산 : %.12lf\t표준편차 : %.12lf\n\n", sum, avg, variance, sqrt(variance)); getchar(); } else printf("없는 명령입니다."); } } return 0; }
void report_auto() { TCHAR appData[MAX_PATH]; FILE *fp; int algorithm, array, count, i; int size_of_array = 0; int *task_array; int *array_selected = 0; bool recalled = FALSE; int cxt = 0; long double *ld_array, sum, variance, avg; char addr[256]; RAND_MIN = 0; RAND_SECTION = 10000000 - 0 + 1; /*if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, appData))) {*/ //sprintf_s(addr, 256, "%s%s%d%s", appData, "\\report_", (int)time(NULL), ".log"); //sprintf_s(addr, 256, "%s%s", "C:", "\\report_.log"); _wfopen_s(&fp, _T("C:\\rollrat\\report_sort.log"), _T("w+")); /*fwprintf(fp, _T("정렬 알고리즘 정밀 측정기으로부터 자동으로 생성되었음.\n\n")); fwprintf(fp, _T("[알고리즘] [배열] [횟수] 순으로 알고리즘 목록이 생성되며, 바로 밑에 합계, 평균, 분산, 표준편차가 기제됩니다. 최대 횟수는 십만번이며, ") _T("천 개 이하의 자료개수에서만 중복없는 임의배열이 적용됩니다. 랜덤최소 값은 0이며 최대값은 10000으로 설정됩니다. 횟수는 모두 10회입니다.\n\n"));*/ for (algorithm = 1; algorithm < 14; algorithm++) { if (algorithm == 11 || algorithm == 7 || algorithm == 8 || algorithm == 9) continue; // 버킷 알고리즘 사용안함 for (array = 0; array < 4; array++) { for (count = 1; count < 5; count++) { //if (count > 3 && array == 2) // break; // 중복없는 임의배열 적용안함 size_of_array = pow(10, count);//(double)((double)count / 2)); SIZE_OF_ARRAY = size_of_array; task_array = (int *)malloc(sizeof(int) * size_of_array); array_direct = (int *)malloc(sizeof(int)*size_of_array); array_reverse = (int *)malloc(sizeof(int)*size_of_array); array_random = (int *)malloc(sizeof(int)*size_of_array); array_overlap = (int *)malloc(sizeof(int)*size_of_array); #define _MAX_COUNT 30 ld_array = (long double *)malloc(sizeof(long double) * _MAX_COUNT); for (i = 0; i < _MAX_COUNT; i++) { selected_array_g = array + 1; init_array(); if (array == 0) array_selected = array_direct; else if (array == 1) array_selected = array_reverse; else if (array == 2) array_selected = array_random; else if (array == 3) array_selected = array_overlap; switch (algorithm) { case 1: timer_start(); sort_selection(array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 2: timer_start(); sort_insertion(array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 3: timer_start(); sort_bubble(array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 4: timer_start(); sort_shell(array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 5: timer_start(); sort_quick0(array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 6: timer_start(); sort_quick1(array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 7: timer_start(); sort_quick2(array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 8: timer_start(); sort_quick3(array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 9: timer_start(); sort_quick4(array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 10: timer_start(); radix_sort(array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 11: timer_start(); sort_bucket(array_selected, SIZE_OF_ARRAY, task_array); timer_finish(); break; case 12: timer_start(); sort_heap(array_selected, SIZE_OF_ARRAY); timer_finish(); break; case 13: timer_start(); sort_merge(array_selected, SIZE_OF_ARRAY, task_array); timer_finish(); break; } ld_array[i] = timer_getns(); } sum = 0.0f; for (i = 0; i < _MAX_COUNT; i++) { sum += ld_array[i]; } avg = sum / _MAX_COUNT; variance = 0.0f; for (i = 0; i < _MAX_COUNT; i++) { variance += pow(ld_array[i] - avg, 2); } variance /= _MAX_COUNT; fwprintf(fp, _T("[%s] [%s] [%s]\n"), sort_name[algorithm - 1], array_name[array], commasput(size_of_array)); fwprintf(fp, _T("합계 : %.12lf ns\n평균 : %.12lf ns\n분산 : %.12lf\n표준편차 : %.12lf\n\n"), sum, avg, variance, sqrt(variance)); printf("[%d/216]완료됨\n", ++cxt); // 오래걸리고 많이하면 과부하걸려서 걍 없앰 /*free(ld_array); free(array_overlap); free(array_random); free(array_reverse); free(array_direct); free(task_array);*/ } } } fwprintf(fp, _T("end")); fclose(fp); //} printf("C:\\rollrat\\report_sort.log에 성공적으로 생성하였습니다."); }
static void sort_heap(const RandomAccessIterator &first, const RandomAccessIterator &last) { sort_heap(first, last, _std_less_comparer<RandomAccessIterator>); }