`sort` C++ Examples
60 C++ code examples are found related to "sort".
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: bubble_sort.c From cosmos with GNU General Public License v3.0 | 14 votes |
void bubbleSort(int a[], int n) { int i, j; bool swapped; for (i = 0; i < n - 1; i++) { swapped = false; for (j = 0; j < n - i - 1; j++) { if (a[j] > a[j + 1]) { swap(&a[j], &a[j + 1]); swapped = true; } } if (swapped == false) break;/*break if array is sorted i.e. no swapping possible*/ } }
Example 2
Source File: btUnionFind.cpp From SimpleRenderEngineProject with MIT License | 7 votes |
void btUnionFind::sortIslands() { //first store the original body index, and islandId int numElements = m_elements.size(); for (int i=0;i<numElements;i++) { m_elements[i].m_id = find(i); #ifndef STATIC_SIMULATION_ISLAND_OPTIMIZATION m_elements[i].m_sz = i; #endif //STATIC_SIMULATION_ISLAND_OPTIMIZATION } // Sort the vector using predicate and std::sort //std::sort(m_elements.begin(), m_elements.end(), btUnionFindElementSortPredicate); m_elements.quickSort(btUnionFindElementSortPredicate()); }
Example 3
Source File: Gnome_Sort.cpp From Algo_Ds_Notes with GNU General Public License v3.0 | 6 votes |
void gnome_sort(int arr[], int n) { // Implementation Logic Begins here int index = 0; while (index < n) { // Intially Index is set to Zero then It will be incremented to 1 if (index == 0) index++; // Checking the values between the array elements if (arr[index] >= arr[index - 1]) index++; else { swap(arr[index], arr[index - 1]); index--; } }
Example 4
Source File: counting_sort.cpp From Algorithms with MIT License | 6 votes |
void Count_Sort(int a[],int n,int k){ int freq[k+1]={0}; for(int i=0;i<n;i++){ ++freq[a[i]]; } int j=0; for(int i=0;i<=k;i++){ int temp=freq[i]; while(temp--){ a[j++]=i; } } }
Example 5
Source File: bucketsort.cpp From Algorithms with MIT License | 6 votes |
void bucketSort(float arr[], int n) { // 1) Create n empty buckets vector<float> b[n]; // 2) Put array elements in different buckets for (int i=0; i<n; i++) { int bi = n*arr[i]; // Index in bucket b[bi].push_back(arr[i]); } // 3) Sort individual buckets for (int i=0; i<n; i++) sort(b[i].begin(), b[i].end()); // 4) Concatenate all buckets into arr[] int index = 0; for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j]; }
Example 6
Source File: 75.sort-colors.cpp From algorithm with MIT License | 6 votes |
void sortColors(vector<int>& nums) { int k = 0; for (auto i = 0; i < nums.size(); ++i) { if (nums[i] == 0) { swap(nums, k, i); k ++; } } for (auto i = k; i < nums.size(); ++i) { if (nums[i] == 1) { swap(nums, k, i); k ++; } } }
Example 7
Source File: ctp_replayer.cpp From LazzyQuant with GNU General Public License v3.0 | 6 votes |
void CtpReplayer::sortTickPairList() { std::sort(ctpMdList.begin(), ctpMdList.end(), [](const auto &item1, const auto &item2) -> bool { return *((int*)item1.ActionDay) < *((int*)item2.ActionDay); // 比较本地时间戳. }); for (const auto &item : qAsConst(ctpMdList)) { const QString instrumentID(item.InstrumentID); int time = hhmmssToSec(item.UpdateTime); CommonTick commonTick = {0, item.LastPrice, item.AskPrice1, item.BidPrice1, item.Volume, item.AskVolume1, item.BidVolume1}; commonTick.setTimeStamp(mapTime(time), item.UpdateMillisec); tickPairList << qMakePair(instrumentID, commonTick); } ctpMdList.clear(); TickReplayer::sortTickPairList(); }
Example 8
Source File: BucketSort.cpp From interview-techdev-guide with MIT License | 6 votes |
void bucketSort(float arr[], int n) { // 1) Create n empty buckets vector<float> b[n]; // 2) Put array elements in different buckets for (int i=0; i<n; i++) { int bi = n*arr[i]; // Index in bucket b[bi].push_back(arr[i]); } // 3) Sort individual buckets for (int i=0; i<n; i++) sort(b[i].begin(), b[i].end()); // 4) Concatenate all buckets into arr[] int index = 0; for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j]; }
Example 9
Source File: SelectionSort.cpp From interview-techdev-guide with MIT License | 6 votes |
void selectionSort(int arr[], int n) { int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); } }
Example 10
Source File: InsertionSort.cpp From interview-techdev-guide with MIT License | 6 votes |
void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } }
Example 11
Source File: sort_insert.cc From datatable with Mozilla Public License 2.0 | 6 votes |
void insert_sort_values_str( const Column& column, size_t strstart, V* o, int n, GroupGatherer& gg, bool descending) { CString i_value, k_value; bool i_valid, k_valid; auto compfn = descending? compare_strings<-1> : compare_strings<1>; int j; o[0] = 0; for (int i = 1; i < n; ++i) { i_valid = column.get_element(static_cast<size_t>(i), &i_value); for (j = i; j > 0; j--) { auto k = o[j - 1]; k_valid = column.get_element(static_cast<size_t>(k), &k_value); int cmp = compfn(i_value, i_valid, k_value, k_valid, strstart); if (cmp != 1) break; o[j] = o[j-1]; } o[j] = static_cast<V>(i); } if (gg) { gg.from_data(column, o, static_cast<size_t>(n)); } }
Example 12
Source File: sort_insert.cc From datatable with Mozilla Public License 2.0 | 6 votes |
void insert_sort_values(const T* x, V* o, int n, GroupGatherer& gg) { o[0] = 0; for (int i = 1; i < n; ++i) { T xival = x[i]; int j = i; while (j && xival < x[o[j - 1]]) { o[j] = o[j - 1]; j--; } o[j] = static_cast<V>(i); } if (gg) { gg.from_data(x, o, static_cast<size_t>(n)); } }
Example 13
Source File: insertion-sort.cpp From tcs-digital-prep with MIT License | 6 votes |
vector <int> insertionSort (vector <int> v) { /** Apply insertion sort on a vector and return the sorted vector */ int l = v.size(); for (int i = 1; i < l; i++) { int current = v[i]; int j = i-1; while (current < v[j] && j >= 0) { v[j+1] = v[j]; j--; } v[j+1] = current; } return v; }
Example 14
Source File: Sort.cpp From awesome-algorithm-question-solution with MIT License | 6 votes |
void selectionSort(int arr[], int n){ for (int i = 0; i < n; i++){ int min = i; for (int j = i + 1; j < n ; ++j) { if (arr[j] < arr[min]){ min = j; } } if (min != i){ __swap(arr[i],arr[min]); } } }
Example 15
Source File: main.cpp From awesome-algorithm-question-solution with MIT License | 6 votes |
void sortColorTest(){ printf("Test for sorting colors:\n"); int arr [] = {0,1,1,2,0,2,1}; int length = sizeof(arr)/ sizeof(int); vector<int> vec(arr, arr + length); printf("\nOriginal vector is:\n"); for (size_t i = 0; i < vec.size(); i++) { cout << vec.at(i) << " "; } ArrayQuestion().sortColors(vec); printf("\nAfter sorting color is:\n"); for (size_t i = 0; i < vec.size(); i++) { cout << vec.at(i) << " "; } }
Example 16
Source File: radix_sort.cpp From Competitive-Programming-Repository with MIT License | 6 votes |
void stableCountingSort(T a[], int d, int n, int (*get)(T, int)){ int position[k] = {}; T b[k]; for (int i = 0; i < n; i++) { ++position[get(a[i], d)]; } for (int i = 1; i < k; i++) { position[i] += position[i-1]; } for (int i = n-1; i >= 0; i--) { b[position[get(a[i], d)]--] = a[i]; } for (int i = 0; i < n; i++) { a[i] = b[i+1]; } }
Example 17
Source File: indirect_sort.cc From epicode with MIT License | 6 votes |
void IndirectSort(const string& file_name) { // Stores file records into A. ifstream ifs(file_name.c_str()); vector<int> A; int x; while (ifs >> x) { A.emplace_back(x); } // Initializes P. vector<const int*> P; for (int& a : A) { P.emplace_back(&a); } // Indirectly sorts file. sort(begin(P), end(P), [](const int* a, const int* b) { return *a < *b; }); // Outputs file. ofstream ofs(file_name.c_str()); for (const int* p : P) { ofs << *p << endl; } }
Example 18
Source File: 0464-Sort Integers II.cpp From LintCode with MIT License | 6 votes |
void quickSort(vector<int>& A, int start, int end) { if (start < end) { int pivot = A[start + (end - start) / 2]; int left = start, right = end; while (left <= right) { while (left <= right && A[left] < pivot) { ++left; } while (left <= right && A[right] > pivot) { --right; } if (left <= right) { swap(A[left], A[right]); ++left; --right; } } quickSort(A, start, right); quickSort(A, left, end); } }
Example 19
Source File: 0173-Insertion Sort List.cpp From LintCode with MIT License | 6 votes |
ListNode * insertionSortList(ListNode * head) { // write your code here ListNode dummy(-1); ListNode* prev = &dummy; ListNode* curr = head; while (curr) { ListNode* next = curr->next; if (!prev->next || prev->next->val > curr->val) { prev = &dummy; } while (prev->next && prev->next->val <= curr->val) { prev = prev->next; } curr->next = prev->next; prev->next = curr; curr = next; } return dummy.next; }
Example 20
Source File: 0148-Sort Colors.cpp From LintCode with MIT License | 6 votes |
void sortColors(vector<int> &nums) { // write your code here int n = nums.size(); if (n == 0) { return; } int i = 0, k = n - 1; int j = 0; while (j <= k) { if (nums[j] == 0) { swap(nums[i++], nums[j++]); } else if (nums[j] == 2) { swap(nums[k--], nums[j]); } else { ++
Example 21
Source File: 0508-Wiggle Sort.cpp From LintCode with MIT License | 6 votes |
void wiggleSort(vector<int>& nums) { // Write your code here if (nums.size() == 0) { return; } for (int i = 0; i < nums.size() - 1; ++i) { if ((i % 2 == 0 && nums[i] > nums[i + 1]) || (i % 2 == 1 && nums[i] < nums[i + 1])) { swap(nums[i], nums[i + 1]); } } }
Example 22
Source File: 0830-String Sort.cpp From LintCode with MIT License | 6 votes |
string stringSort(string &str) { // Write your code here unordered_map<char, int> table; for (char c : str) { ++table[c]; } priority_queue<Node> pq; for (auto t : table) { pq.emplace(t.first, t.second); } string result; while (!pq.empty()) { result += string(pq.top().count, pq.top().c); pq.pop(); } return result; }
Example 23
Source File: selection_sort.cpp From Hacktoberfest with MIT License | 6 votes |
void selectionSort(int arr[], int n) { int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); } }
Example 24
Source File: sort01.cpp From Hacktoberfest with MIT License | 6 votes |
void SortZeroesAndOne(int arr[], int n){ /* Don't write main(). * Don't read input, it is passed as function argument. * Update in the given array itself. Don't return or print anything. * Taking input and printing output is handled automatically. */ int p=0; int i=1,c=1; while(p<n&&c<n) { int temp; if(arr[p]>arr[c]) { temp=arr[p]; arr[p]=arr[c]; arr[c]=temp; p++; } else if(arr[p]==arr[c]) { if(arr[p]==0){ c++; p++;} else c++; }
Example 25
Source File: heapsort.cpp From Hacktoberfest with MIT License | 6 votes |
void heapSort(int arr[], int n) { // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i=n-1; i>=0; i--) { // Move current root to end swap(arr[0], arr[i]); // call max heapify on the reduced heap heapify(arr, i, 0); } }
Example 26
Source File: Insertion_sort.cpp From Hacktoberfest with MIT License | 6 votes |
void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } }
Example 27
Source File: vlistue.cpp From vnote with MIT License | 6 votes |
void VListUE::sort(int p_id) { Q_UNUSED(p_id); static bool noteFirst = false; int cnt = m_listWidget->count(); if (noteFirst) { int idx = cnt - 1; while (true) { if (itemResultData(m_listWidget->item(idx))->m_type != VSearchResultItem::Note) { // Move it to the first row. m_listWidget->moveItem(idx, 0); } else { break; } } }
Example 28
Source File: vlistfolderue.cpp From vnote with MIT License | 6 votes |
void VListFolderUE::sort(int p_id) { Q_UNUSED(p_id); static bool noteFirst = false; int cnt = m_listWidget->count(); if (noteFirst) { int idx = cnt - 1; while (true) { if (itemResultData(m_listWidget->item(idx))->m_type != VSearchResultItem::Note) { // Move it to the first row. m_listWidget->moveItem(idx, 0); } else { break; } } }
Example 29
Source File: ceshi29.cpp From project-in-BUPT with MIT License | 6 votes |
void bubbleSort(int*a,int n) { int i,pass,temp; for(pass=1;pass<=n-1;pass++)//for(loc=size-1;loc>=1;loc--) { for(i=0;i<=n-pass-1;i++)//for(i=0;i<=loc-1;i++) { if(a[i]<a[i+1]) { temp=a[i+1]; a[i+1]=a[i]; a[i]=temp; } } } }
Example 30
Source File: 排序的时间比较.cpp From project-in-BUPT with MIT License | 6 votes |
void insertSort(int arr[],int start,int end) { int p; for(int i=start+1;i<=end;i++) { arr[0]=arr[i]; for(p=i;p>=1;p--) { if(arr[0]<=arr[p]&&arr[0]>arr[p-1])//hint: <= must be put firstly to break break; } for(int j=i-1;j>=p;j--) { arr[j+1]=arr[j]; } arr[p]=arr[0]; } }
Example 31
Source File: lp_primal_core_solver.cpp From lean2 with Apache License 2.0 | 6 votes |
::sort_non_basis() { for (unsigned j : this->m_non_basic_columns) { T const & da = this->m_d[j]; this->m_steepest_edge_coefficients[j] = da * da / this->m_column_norms[j]; } std::sort(this->m_non_basic_columns.begin(), this->m_non_basic_columns.end(), [this](unsigned a, unsigned b) { return this->m_steepest_edge_coefficients[a] > this->m_steepest_edge_coefficients[b]; }); m_non_basis_list.clear(); // reinit m_basis_heading for (unsigned j = 0; j < this->m_non_basic_columns.size(); j++) { unsigned col = this->m_non_basic_columns[j]; this->m_basis_heading[col] = - static_cast<int>(j) - 1; m_non_basis_list.push_back(col); } }
Example 32
Source File: sort.cpp From alive2 with MIT License | 6 votes |
vector<unsigned> top_sort(const edgesTy &edges) { vector<unsigned> sorted; vector<unsigned char> marked; marked.resize(edges.size()); function<void(unsigned)> visit = [&](unsigned v) { if (marked[v]) return; marked[v] = true; for (auto child : edges[v]) { visit(child); } sorted.emplace_back(v); }; for (unsigned i = 1, e = edges.size(); i < e; ++i) visit(i); if (!edges.empty()) visit(0); reverse(sorted.begin(), sorted.end()); return sorted; }
Example 33
Source File: quick_sort.cpp From blog_codes with GNU General Public License v3.0 | 6 votes |
void quickSort(int *ary, int start, int end) { int pivot = ary[start]; int l = start, r = end; while (l <= r) { while (l <= r && ary[l] < pivot) l ++; while (l <= r && ary[r] > pivot) r --; if (l <= r) { swap(ary[r--], ary[l++]); } } if (start < r) { quickSort(ary, start, r); } if (l < end) { quickSort(ary, l, end); } }
Example 34
Source File: counting_sort.cpp From HacktoberFestContribute with MIT License | 6 votes |
void CounterSort(int a[], int n, int r, int lower) { int i, j = 0, counter[r] = {0}; // Counting the number occurrence of each element. for(i=0; i<n; i++) counter[a[i]-lower]++; i=0; // placing the elements back into array. while(i < r) { flag: a[j] = lower+i; j++; counter[i]--; // place the same element until its counter is zero. if(counter[i] > 0) goto flag; i++; } }
Example 35
Source File: quick_sort.cpp From HacktoberFestContribute with MIT License | 6 votes |
void quick_sort(int a[], int left, int right) { int i = left, j = right; int pivot = a[right]; while (i <= j) { while (a[i] < pivot) i++; //carry on, this part already sorted while (a[j] > pivot) j--; //carry on, this part already sorted if (i <= j) { // a[i]>=pivot and a[j]<=pivot //swap a[i] with a[j] int tmp = a[i]; a[i] = a[j]; a[j] = tmp; i++; j--; } } if (left < j) quick_sort(a, left, j); if (i < right) quick_sort(a, i, right); }
Example 36
Source File: InsertionSort.cpp From HacktoberFestContribute with MIT License | 6 votes |
void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i-1; while (j >= 0 && arr[j] > key) { arr[j+1] = arr[j]; j = j-1; } arr[j+1] = key; } }
Example 37
Source File: BubbleSort.cpp From HacktoberFestContribute with MIT License | 6 votes |
void bubbleSort(int A[],int n) { int i,j; int temp; for(i=0;i<n;i++) { for(j=0;j<n-i;j++) { if(A[j]>A[j+1]) { temp=A[j]; A[j]=A[j+1]; A[j+1]=temp; } } } }
Example 38
Source File: shell_sort.cpp From HacktoberFestContribute with MIT License | 6 votes |
void insertion_sort(int a[], int a_size) { int i = 0; while (i < a_size) { int j = i; while (j > 0 && a[j-1] > a[j]) { // swap int temp = a[j-1]; a[j-1] = a[j]; a[j] = temp; j--; } i++; } cout << "After insertion sort: "; for (int i = 0; i < a_size; i++) { cout << a[i] << " "; } cout << std:: endl; }
Example 39
Source File: Selection_sort.cpp From HacktoberFestContribute with MIT License | 6 votes |
int selection_sort(int* arr, int size) { int max, max_ind, i; for( i=0 ; i<size ; i++) { max = arr[i]; max_ind = i; for(int j=i; j<size ; j++ ) { if(arr[j]>max) { max = arr[j]; max_ind = j; } } arr[max_ind] = arr[i]; arr[i] = max; } }
Example 40
Source File: RadixSort.cpp From HacktoberFestContribute with MIT License | 6 votes |
void radixSortUsingQueueSTL(int arr[], int n) { queue<int> q[10]; int max = getMax(arr, n); int maxDigits = 0; while(max > 0) { maxDigits++; max /= 10; } int currPow = 1; for(int i = 0;i < maxDigits;i++) { for(int j = 0;j < n;j++) { int currIdx = (arr[j] / currPow) % 10; q[currIdx].push(arr[j]); } int idx = 0; for(int j = 0;j < 10;j++) { while(!q[j].empty()) { arr[idx++] = q[j].front(); q[j].pop(); } } currPow *= 10; } }
Example 41
Source File: IntroSort_C++_Sorting_Weapon.cpp From Self-Made-Projects with MIT License | 6 votes |
void InsertionSort(int arr[], int *begin, int *end) { // Get the left and the right index of the subarray // to be sorted int left = begin - arr; int right = end - arr; for (int i = left+1; i <= right; i++) { int key = arr[i]; int j = i-1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= left && arr[j] > key) { arr[j+1] = arr[j]; j = j-1; } arr[j+1] = key; } return; }
Example 42
Source File: Gnome_Sort.cpp From Self-Made-Projects with MIT License | 6 votes |
void gnomeSort(int arr[], int n) { int index = 0; while (index < n) { if (index == 0) index++; if (arr[index] >= arr[index-1]) index++; else { swap(arr[index], arr[index-1]); index--; } }
Example 43
Source File: Enclave.cpp From opaque with Apache License 2.0 | 6 votes |
void ecall_partition_for_sort(uint8_t *sort_order, size_t sort_order_length, uint32_t num_partitions, uint8_t *input_rows, size_t input_rows_length, uint8_t *boundary_rows, size_t boundary_rows_length, uint8_t **output_partitions, size_t *output_partition_lengths) { // Guard against operating on arbitrary enclave memory assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1); assert(sgx_is_outside_enclave(boundary_rows, boundary_rows_length) == 1); sgx_lfence(); try { partition_for_sort(sort_order, sort_order_length, num_partitions, input_rows, input_rows_length, boundary_rows, boundary_rows_length, output_partitions, output_partition_lengths); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } }
Example 44
Source File: 0147-Insertion Sort List.cpp From LeetCode with MIT License | 6 votes |
ListNode* insertionSortList(ListNode* head) { ListNode dummy(-1); ListNode* prev = &dummy; ListNode* curr = head; while (curr) { ListNode* next = curr->next; if (!prev->next || prev->next->val > curr->val) { prev = &dummy; } while (prev->next && prev->next->val <= curr->val) { prev = prev->next; } curr->next = prev->next; prev->next = curr; curr = next; } return dummy.next; }
Example 45
Source File: shell_sort2.cpp From C-Plus-Plus with MIT License | 6 votes |
void shell_sort(T *arr, size_t LEN) { const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; const unsigned int gap_len = 8; size_t i, j, g; for (g = 0; g < gap_len; g++) { unsigned int gap = gaps[g]; for (i = gap; i < LEN; i++) { T tmp = arr[i]; for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) { arr[j] = arr[j - gap]; } arr[j] = tmp; } } }
Example 46
Source File: bucket_sort.cpp From C-Plus-Plus with MIT License | 6 votes |
void bucketSort(float arr[], int n) { // 1) Create n empty buckets std::vector<float> *b = new std::vector<float>[n]; // 2) Put array elements in different buckets for (int i = 0; i < n; i++) { int bi = n * arr[i]; // Index in bucket b[bi].push_back(arr[i]); } // 3) Sort individual buckets for (int i = 0; i < n; i++) std::sort(b[i].begin(), b[i].end()); // 4) Concatenate all buckets into arr[] int index = 0; for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j]; delete[] b; }
Example 47
Source File: non_recursive_merge_sort.cpp From C-Plus-Plus with MIT License | 6 votes |
void non_recursive_merge_sort(const Iterator first, const Iterator last, const size_t n) { // create a buffer large enough to store all elements // dynamically allocated to comply with cpplint char* buffer = new char[n * sizeof(*first)]; // buffer size can be optimized to largest power of 2 less than n // elements divide the container into equally-sized segments whose // length start at 1 and keeps increasing by factors of 2 for (size_t length(1); length < n; length <<= 1) { // merge adjacent segments whose number is n / (length * 2) Iterator left(first); for (size_t counter(n / (length << 1)); counter; --counter) { Iterator right(left + length), end(right + length); merge(left, right, end, buffer); left = end; } // if the number of remaining elements (n * 2 % length) is longer // than a segment, merge the remaining elements if ((n & ((length << 1) - 1)) > length) merge(left, left + length, last, buffer); } delete[] buffer; }
Example 48
Source File: comb_sort.cpp From Algo_Ds_Notes with GNU General Public License v3.0 | 6 votes |
void combSort(int arr[], int n) { // initialize gap with array length int gap = n; int flag= 1; while (gap > 1 || flag == 1) { // updating gap value by using shrink factor as 1.3 gap = (gap * 10) / 13; // if Gap is less than 1, take gap as 1 gap= max(1,gap); flag= 0; // Compare all elements with the obtained gap value for (int i = 0; i < (n - gap); i++) { // Swap arr[i] and arr[i+gap] if arr[i] is greater if (arr[i] > arr[i + gap]) { swap(arr[i], arr[i+gap]); flag= 1; } } } }
Example 49
Source File: Shell_Sort.cpp From Algo_Ds_Notes with GNU General Public License v3.0 | 6 votes |
int Shell_Sort(int array[], int size) { for(int gap = size / 2; gap > 0; gap /= 2) { for(int i = gap; i < size; i++) { int temp = array[i], j; for(j = i; j >= gap && array[j - gap] > temp; j -= gap) array[j] = array[j - gap]; array[j] = temp; } } return 0; }
Example 50
Source File: Quicksort2-Sorting.cpp From HackerRank with MIT License | 6 votes |
vector<int> quickSort(vector<int>& arr) { vector<int> left, right; int f; if(arr.size() <= 1) return arr; f = arr[0]; for(int i = 1; i < arr.size(); i++){ if(arr[i] <= f) left.push_back(arr[i]); else right.push_back(arr[i]); }
Example 51
Source File: Quicksort1-Partition.cpp From HackerRank with MIT License | 6 votes |
void quickSort(int arr[], int f, int l) { int i, j; if(f < l){ i = f + 1; j = l; while(arr[i] < arr[f]) i++; while(arr[j] > arr[f]) j--; while(i < j){ swap(arr[i], arr[j]); while(arr[i] < arr[f]) i++; while(arr[j] > arr[f]) j--; } swap(arr[j], arr[f]); } }
Example 52
Source File: InsertionSort-Part1.cpp From HackerRank with MIT License | 6 votes |
void insertionSort(vector<int>ar) { int j = ar.size() - 1; int last = ar[j]; while(j >= 1 && ar[j - 1] > last){ ar[j] = ar[j - 1]; j--; for(int i = 0; i < ar.size(); i++) cout << ar[i] << " "; cout << endl; } ar[j] = last; for(int i = 0; i < ar.size(); i++) cout << ar[i] << " "; cout << endl; }
Example 53
Source File: 0791-Custom Sort String.cpp From LeetCode with MIT License | 6 votes |
string customSortString(string S, string T) { string result; vector<int> table(26); for (char c : T) { ++table[c - 'a']; } for (char c : S) { if (table[c - 'a'] > 0) { result += string(table[c - 'a'], c); table[c - 'a'] = 0; } } for (int i = 0; i < 26; ++i) { if (table[i] > 0) { result += string(table[i], 'a' + i); } } return result; }
Example 54
Source File: 0451-Sort Characters By Frequency.cpp From LeetCode with MIT License | 6 votes |
string frequencySort(string s) { unordered_map<char, int> table; for (char c : s) { ++table[c]; } priority_queue<pair<int, char>> pq; for (auto& p : table) { pq.push({p.second, p.first}); } string result; while (!pq.empty()) { auto p = pq.top(); pq.pop(); result += string(p.first, p.second); } return result; }
Example 55
Source File: 0324-Wiggle Sort II.cpp From LeetCode with MIT License | 6 votes |
void wiggleSort(vector<int>& nums) { int n = nums.size(); if (n == 0) { return; } auto midptr = nums.begin() + n / 2; nth_element(nums.begin(), midptr, nums.end()); int mid = *midptr; int i = 0, j = 0, k = n - 1; while (j <= k) { int index = Index(j , n); if (nums[index] > mid) { swap(nums[index], nums[Index(i++, n)]); ++j; } else if (nums[index] < mid) { swap(nums[index], nums[Index(k--, n)]); } else { ++
Example 56
Source File: Bubble_Sort.cpp From Algo_Ds_Notes with GNU General Public License v3.0 | 6 votes |
void Bubble_Sort(int array[], int size) { int temp, flag; // flag keeps track if any swap happened or not, if swap not happened then array is sorted and it will break out of the loop // and will save time from running for loop unnecessarily for (int i = 0; i < size - 1; i++) { flag = 0; for (int j = 0; j < size - i - 1; j++) { // Do swapping if (array[j] > array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; flag++; } } if (!flag) break; } }
Example 57
Source File: Radix_Sort.cpp From Algo_Ds_Notes with GNU General Public License v3.0 | 6 votes |
void Counting_Sort(int array[], int size, int exp) { int output[size]; int i, count[10] = {0}; for(i = 0; i < size; i++) count[(array[i] / exp) % 10]++; for(i = 1; i < 10; i++) count[i] += count[i - 1]; for(i = size - 1; i >= 0; i--) { output[count[(array[i] / exp) % 10] - 1] = array[i]; count[(array[i] / exp) % 10]--; } for(i = 0; i < size; i++) array[i] = output[i]; }
Example 58
Source File: Binary_Insertion_Sort.cpp From Algo_Ds_Notes with GNU General Public License v3.0 | 6 votes |
void insertionSort(int arr[], int size) { int i, location, j, k, key; for (i = 1; i < size; ++i) { j = i - 1; key = arr[i]; //to find location where key sould be inserted location = binarySearch(arr, key, 0, j); // to move all elements after location to create space for key while (j >= location) { arr[j+1] = arr[j]; j--; } arr[j+1] = key; } }
Example 59
Source File: heapsort.cpp From hacktoberfest-2018 with MIT License | 6 votes |
void heapSort(int arr[], int n) { // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i=n-1; i>=0; i--) { // Move current root to end swap(arr[0], arr[i]); // call max heapify on the reduced heap heapify(arr, i, 0); } }
Example 60
Source File: 0912-Sort an Array.cpp From LeetCode with MIT License | 6 votes |
void mergeSort(vector<int>& nums, int start, int end, vector<int>& temp) { if (start < end) { int mid = (start + end) / 2; mergeSort(nums, start, mid, temp); mergeSort(nums, mid + 1, end, temp); int i = start, j = mid + 1, k = start; while (i <= mid) { while (j <= end && nums[j] < nums[i]) { temp[k++] = nums[j++]; } temp[k++] = nums[i++]; } while (j <= end) { temp[k++] = nums[j++]; } for (int i = start; i <= end; ++i) { nums[i] = temp[i]; } } }