C++ Code Examples for sort

60 C++ code examples are found related to "sort". These examples are extracted from open source projects. 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
Project: DS-Algo-Handbook   Author: salman-bhai   File: shell-sort.cpp    License: MIT License 6 votes vote down vote up
void sortIt( int* arr )
    {
	bool sorted = false;
	while( true )
	{
	    sorted = true;
	    int st = 0;
	    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )
	    {
		if( arr[st] > arr[x] )
		{ swap( arr[st], arr[x] ); sorted = false; }
		st = x;
	    }
	    if( ++_idx >= 8 ) _idx = 8;
	    if( sorted && _idx == 8 ) break;
	}
    } 
Example 2
Project: algorithms   Author: priyankchheda   File: OddEvenSort.cpp    License: MIT License 6 votes vote down vote up
void OddEvenSort(T data[], int dataLen) {
    bool sorted = false;

    while (true) {
        sorted = true;
        for (int i = 1; i < dataLen-1; i += 2) {
            if (data[i] > data[i+1]) {
                std::swap(data[i], data[i+1]);
                sorted = false;
            }
        }
        for (int i = 0; i < dataLen-1; i += 2) {
            if (data[i] > data[i+1]) {
                std::swap(data[i], data[i+1]);
                sorted = false;
            }
        }
        if (sorted) {
            break;
        }
    }
} 
Example 3
Project: open_source_startalk   Author: qunarcorp   File: combinationitemsortproxymodel.cpp    License: MIT License 6 votes vote down vote up
bool CombinationItemSortProxyModel::lessThan( const QModelIndex &left, const QModelIndex &right ) const
{
    bool desc = false;

    QList<QString> sortids;
    sortids << Util::WorkPlaceId;
	sortids << Util::StarPersonId;
    sortids << Util::GroupsId;
    sortids << Util::OrganizationId;
    sortids << Util::FriendsId;
    sortids << Util::SUBSCRIPTIONNUM_ID;
    sortids << Util::BlackFriendsId;
    
    QString leftId = left.data(CombinationItem::Combinationid).toString ();
    QString rightId = right.data(CombinationItem::Combinationid).toString ();

    if (!leftId.isEmpty() && !rightId.isEmpty())
    {
        if (sortids.contains (leftId) && !sortids.contains (rightId))
            return !desc;
        else if (!sortids.contains (leftId) && sortids.contains (rightId))
            return desc;
        else
            return 
Example 4
Project: CPP-Data-Structures-and-Algorithms   Author: PacktPublishing   File: Quick_Sort.cpp    License: MIT License 6 votes vote down vote up
void QuickSort(
    int arr[],
    int startIndex,
    int endIndex)
{
    // Only perform sort process
    // if the end index is higher than start index
    if (startIndex < endIndex)
    {
        // Retrieve pivot position from Partition() function
        // This pivotIndex is the index of element that is already
        // in correct position
        int pivotIndex = Partition(arr, startIndex, endIndex);

        // Sort left sublist
        // arr[startIndex ... pivotIndex - 1]
        QuickSort(arr, startIndex, pivotIndex - 1);

        // Sort right sublist
        // arr[pivotIndex + 1 ... endIndex]
        QuickSort(arr, pivotIndex + 1, endIndex);
    }
} 
Example 5
Project: vnote   Author: tamlok   File: vlistue.cpp    License: MIT License 6 votes vote down vote up
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 6
Project: Spike   Author: OFTNAI   File: SpikingSynapses.cpp    License: MIT License 6 votes vote down vote up
void SpikingSynapses::sort_synapses(){
  
  int* temp_delay_array = (int*)malloc(total_number_of_synapses * sizeof(int));
  int* temp_synlabel_array = (int*)malloc(total_number_of_synapses * sizeof(int));
  // Re-ordering arrays
  for (int s=0; s < total_number_of_synapses; s++){
    temp_delay_array[s] = delays[synapse_sort_indices[s]];
    temp_synlabel_array[s] = syn_labels[synapse_sort_indices[s]];
  }

  free(delays);
  free(syn_labels);

  delays = temp_delay_array;
  syn_labels = temp_synlabel_array;
} 
Example 7
Project: Algo_Ds_Notes   Author: jainaman224   File: Gnome_Sort.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
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 8
Project: opaque   Author: mc2-project   File: Sort.cpp    License: Apache License 2.0 6 votes vote down vote up
void sort_single_encrypted_block(
  SortedRunsWriter &w,
  const tuix::EncryptedBlock *block,
  FlatbuffersSortOrderEvaluator &sort_eval) {

  EncryptedBlockToRowReader r;
  r.reset(block);
  std::vector<const tuix::Row *> sort_ptrs(r.begin(), r.end());

  std::sort(
    sort_ptrs.begin(), sort_ptrs.end(),
    [&sort_eval](const tuix::Row *a, const tuix::Row *b) {
      return sort_eval.less_than(a, b);
    });

  for (auto it = sort_ptrs.begin(); it != sort_ptrs.end(); ++it) {
    w.append(*it);
  }
  w.finish_run();
} 
Example 9
Project: LintCode   Author: jiadaizhao   File: 0148-Sort Colors.cpp    License: MIT License 6 votes vote down vote up
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 10
Project: algorithms   Author: priyankchheda   File: ShellSort.cpp    License: MIT License 6 votes vote down vote up
void ShellSort(T data[], int dataLen) {
    int h = 1;
    while (h < dataLen / 3) {
        h = (h * 3) + 1;
    }

    while (h >= 1) {
        // h-sort the array
        for (int i = h; i < dataLen; i++) {
            for (int j = i; j >= h && data[j] < data[j - h]; j = j - h) {
                std::swap(data[j], data[j - h]);
            }
        }
        h = h / 3;
    }
} 
Example 11
Project: C-Plus-Plus   Author: TheAlgorithms   File: counting_sort_string.cpp    License: MIT License 6 votes vote down vote up
void countSort(string arr) {
    string output;

    int count[256], i;
    for (int i = 0; i < 256; i++) count[i] = 0;

    for (i = 0; arr[i]; ++i) ++count[arr[i]];

    for (i = 1; i < 256; ++i) count[i] += count[i - 1];

    for (i = 0; arr[i]; ++i) {
        output[count[arr[i]] - 1] = arr[i];
        --count[arr[i]];
    }

    for (i = 0; arr[i]; ++i) arr[i] = output[i];

    cout << "Sorted character array is " << arr;
} 
Example 12
Project: se2lam   Author: izhengfan   File: MapStorage.cpp    License: MIT License 6 votes vote down vote up
void MapStorage::sortMapPoints() {
    // Remove null MPs
    {
        vector<PtrMapPoint> vMPs;
        vMPs.reserve(mvMPs.size());
        for(int i = 0, iend = mvMPs.size(); i < iend; i++) {
            PtrMapPoint pMP = mvMPs[i];
            if(pMP->isNull() || !(pMP->isGoodPrl()) )
                continue;
            vMPs.push_back(pMP);
        }
        std::swap(vMPs, mvMPs);
    }

    // Change Id of MP to be vector index
    for(int i = 0, iend = mvMPs.size(); i < iend; i++) {
        PtrMapPoint pMP = mvMPs[i];
        pMP->mId = i;
    }

} 
Example 13
Project: cosmos   Author: OpenGenus   File: dutch_national_flag.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
void flagSort(vector<int> &v)
{
    int lo = 0;
    int hi = v.size() - 1;
    int mid = 0;

    while (mid <= hi)
        switch (v[mid])
        {
        case 0:
            swap(v[lo++], v[mid++]);
            break;
        case 1:
            mid++;
            break;
        case 2:
            swap(v[mid], v[hi--]);
            break;
        }
} 
Example 14
Project: C-Plus-Plus   Author: TheAlgorithms   File: counting_sort.cpp    License: MIT License 6 votes vote down vote up
int *Counting_Sort(int Arr[], int N) {
    int max = Max(Arr, N);
    int min = Min(Arr, N);
    int *Sorted_Arr = new int[N];

    int *Count = new int[max - min + 1];

    for (int i = 0; i < N; i++) Count[Arr[i] - min]++;

    for (int i = 1; i < (max - min + 1); i++) Count[i] += Count[i - 1];

    for (int i = N - 1; i >= 0; i--) {
        Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i];
        Count[Arr[i] - min]--;
    }

    return Sorted_Arr;
} 
Example 15
Project: LintCode   Author: jiadaizhao   File: 0830-String Sort.cpp    License: MIT License 6 votes vote down vote up
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 16
Project: hoomd-blue   Author: glotzerlab   File: test_particle_group.cc    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
UP_TEST( ParticleGroup_sort_test )
    {
    std::shared_ptr<SystemDefinition> sysdef = create_sysdef();
    std::shared_ptr<ParticleData> pdata = sysdef->getParticleData();

    std::shared_ptr<ParticleSelector> selector04(new ParticleSelectorTag(sysdef, 0, 4));
    ParticleGroup tags04(sysdef, selector04);
    // verify the initial set
    CHECK_EQUAL_UINT(tags04.getNumMembers(), 5);
    CHECK_EQUAL_UINT(tags04.getIndexArray().getNumElements(), 5);
    for (unsigned int i = 0; i < 5; i++)
        {
        CHECK_EQUAL_UINT(tags04.getMemberTag(i), i);
        CHECK_EQUAL_UINT(tags04.getMemberIndex(i), i);
        }

    for (unsigned int i = 0; i < pdata->getN(); i++)
        {
        if (i <= 4)
            UP_ASSERT(tags04.isMember(i));
        else
            UP_ASSERT(!tags04.isMember(i));
        } 
Example 17
Project: algorithms_with_git   Author: NJACKWinterOfCode   File: Bucket_sort.cpp    License: MIT License 6 votes vote down vote up
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 18
Project: Programmers-Community   Author: shoaibrayeen   File: SolutionByDivyansh.cpp    License: MIT License 6 votes vote down vote up
int bubbleSort(int A[],int size)
{
	int temp;

	for(int i=0;i<size-1;i++)
	{
		for(int j=0;j<size-i-1;j++)
		{
			if(A[j] > A[j+1])
			{
				temp=A[j];
			        A[j]=A[j+1];
				A[j+1]=temp;	
			}
		}
	}
  
	return 0;
} 
Example 19
Project: Algo_Ds_Notes   Author: jainaman224   File: Radix_Sort.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
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 20
Project: WebRTC-APM-for-Android   Author: dengzikun   File: network.cc    License: Apache License 2.0 6 votes vote down vote up
bool SortNetworks(const Network* a, const Network* b) {
  // Network types will be preferred above everything else while sorting
  // Networks.

  // Networks are sorted first by type.
  if (a->type() != b->type()) {
    return a->type() < b->type();
  }

  IPAddress ip_a = a->GetBestIP();
  IPAddress ip_b = b->GetBestIP();

  // After type, networks are sorted by IP address precedence values
  // from RFC 3484-bis
  if (IPAddressPrecedence(ip_a) != IPAddressPrecedence(ip_b)) {
    return IPAddressPrecedence(ip_a) > IPAddressPrecedence(ip_b);
  }

  // TODO(mallinath) - Add VPN and Link speed conditions while sorting.

  // Networks are sorted last by key.
  return a->key() > b->key();
} 
Example 21
Project: NiuTensor   Author: NiuTrans   File: Sort.cpp    License: Apache License 2.0 6 votes vote down vote up
void _Sort(const XTensor * a, XTensor * b, XTensor * index, int dim)
{
    dim = MODX(dim, a->order);
    
    CheckNTErrors((_IsSameShaped(a, b)), "Input tensors should have the same type!");
    CheckNTErrors((dim >= 0 && dim < a->order), "Incorrect dimension specified!");
    CheckNTErrors((a->order == index->order), "Unmatched input tensors!");
    CheckNTErrors((index->dataType == X_INT), "Wrong data type!");

    /* make the index tensor */
    SetAscendingOrder(*index, dim);

    if (a->devID >= 0) {
#ifdef USE_CUDA
        _CudaSortBig(a, b, index, index, dim);
#else
        ShowNTErrors("Plesae specify USE_CUDA and recompile the code!");
#endif
    }
    else { 
Example 22
Project: Hacktoberfest   Author: shivaylamba   File: sort01.cpp    License: MIT License 6 votes vote down vote up
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 23
Project: cosmos   Author: OpenGenus   File: bubble_sort.c    License: GNU General Public License v3.0 6 votes vote down vote up
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 24
Project: SimpleRenderEngineProject   Author: mortennobel   File: btUnionFind.cpp    License: MIT License 6 votes vote down vote up
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 25
Project: Programmers-Community   Author: shoaibrayeen   File: SolutionByFuzail.cpp    License: MIT License 6 votes vote down vote up
void sort(int arr[] , int n)
{
    int temp ;
    for (int i=0 ; i<n ; i++)
    {
        for (int j=0 ; j<n-1-i ; j++)
        {
            if(arr[j]>arr[j+1])
            {
                temp = arr[j] ;
                arr[j] = arr[j+1] ;
                arr[j+1] = temp ;
            }
        }
    }
    for (int i=0 ; i<n ; i++)
    {
        cout << arr[i] << " " ;  
    }
    return ;
} 
Example 26
Project: Algorithms   Author: memr5   File: counting_sort.cpp    License: MIT License 6 votes vote down vote up
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 27
Project: cosmos   Author: OpenGenus   File: shell_sort.c    License: GNU General Public License v3.0 6 votes vote down vote up
void shell_sort(int *a, int n)
{
  int i, j, gap, temp;

  /* Assess the array in gaps starting at half the array size - Each gap is a sublist of 2 values */
  for(gap = n/2 ; gap > 0 ; gap /= 2)
  {
    /* Index at the right value of each gap */
    for(i = gap ; i < n ; i++)
    {
      /* Take a copy of the value under inspection */
      temp = a[i];
      for(j = i ; j >= gap ; j-= gap)
      {
        /* Compare the values in the sub lists and swap where necessary */
        if(temp < a[j-gap])
          a[j] = a[j-gap];
        else
          break;
      }
      a[j] = temp;
    }
  } 
Example 28
Project: Arduino_BLE_iOS_CPP   Author: LessonStudio   File: btUnionFind.cpp    License: MIT License 6 votes vote down vote up
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 29
Project: WangDao-DataStructure   Author: anbingxu666   File: 双向冒泡排序.cpp    License: Apache License 2.0 6 votes vote down vote up
void BubbleSort(ElemType a[], int n) {
    int left = 0;
    int right = n - 1;//left 和right代表待排序部分的左右边界
    int flag = true;//用于优化冒泡排序的flag
    while (left < right && flag) {
        flag = false;//置标志为
        //从左向右边冒泡排序
        for (int i = left; i < right; ++i) {
            if (a[i] > a[i + 1]) {
                swap(&a[i], &a[i + 1]);
                flag = true;
            }
        }
        right--;//最高部分每排好一个元素右边界减1

        for (int i = right; i > left; --i) {
            if (a[i] < a[i - 1]) {
                swap(&a[i], &a[i - 1]);
                flag = true;
            }
        }
        left++;//最低部分每排好一个元素左边界加1

    }
} 
Example 30
Project: SPlisHSPlasH   Author: InteractiveComputerGraphics   File: SimulationDataIISPH.cpp    License: MIT License 6 votes vote down vote up
void SimulationDataIISPH::performNeighborhoodSearchSort()
{
	Simulation *sim = Simulation::getCurrent();
	const unsigned int nModels = sim->numberOfFluidModels();

	for (unsigned int i = 0; i < nModels; i++)
	{
		FluidModel *fm = sim->getFluidModel(i);
		const unsigned int numPart = fm->numActiveParticles();
		if (numPart != 0)
		{
			auto const& d = sim->getNeighborhoodSearch()->point_set(fm->getPointSetIndex());
			d.sort_field(&m_aii[i][0]);
			d.sort_field(&m_dii[i][0]);
			d.sort_field(&m_dij_pj[i][0]);
			d.sort_field(&m_density_adv[i][0]);
			d.sort_field(&m_pressure[i][0]);
			d.sort_field(&m_lastPressure[i][0]);
			d.sort_field(&m_pressureAccel[i][0]);
		}
	}
} 
Example 31
Project: Algorithms   Author: memr5   File: bucketsort.cpp    License: MIT License 6 votes vote down vote up
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 32
Project: opaque   Author: mc2-project   File: Enclave.cpp    License: Apache License 2.0 6 votes vote down vote up
void ecall_non_oblivious_sort_merge_join(uint8_t *join_expr, size_t join_expr_length,
                                         uint8_t *input_rows, size_t input_rows_length,
                                         uint8_t *join_row, size_t join_row_length,
                                         uint8_t **output_rows, size_t *output_rows_length) {
  // Guard against operating on arbitrary enclave memory
  assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1);
  assert(sgx_is_outside_enclave(join_row, join_row_length) == 1);
  sgx_lfence();

  try {
    non_oblivious_sort_merge_join(join_expr, join_expr_length,
                                  input_rows, input_rows_length,
                                  join_row, join_row_length,
                                  output_rows, output_rows_length);
  } catch (const std::runtime_error &e) {
    ocall_throw(e.what());
  }
} 
Example 33
Project: WangDao-DataStructure   Author: anbingxu666   File: 选择排序.cpp    License: Apache License 2.0 6 votes vote down vote up
void selectSort(int *a, int len) {

    for (int i = 0; i < len - 1; ++i) {
        //选出最小的下标
        int minIndex = i;
        for(int j = i + 1;j < len;++j){
            if(a[minIndex] > a[j]){
                minIndex = j;
            }

            //交换元素位置
            if(minIndex!= i){
                int temp = a[minIndex];
                a[minIndex] = a[i];
                a[i] = temp;
            }
        }
    }
} 
Example 34
Project: C-Plus-Plus   Author: TheAlgorithms   File: shell_sort2.cpp    License: MIT License 6 votes vote down vote up
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 35
Project: cosmos   Author: OpenGenus   File: comb_sort.c    License: GNU General Public License v3.0 6 votes vote down vote up
void 
combSort(int ar[], int n)
{
    int gap = n;
    int flag = 0;
    while (gap > 1 || flag == 1) {
        gap = updateGap(gap);
        flag = 0;
        for (int i = 0; i < (n - gap); i++) {
            int x;
            if (ar[i] > ar[i + 1]) {
               x = ar[i];
               ar[i] = ar[i + 1];
               ar[i + 1] = x;
               flag = 1;
            }
        }
    }
} 
Example 36
Project: Algo_Ds_Notes   Author: jainaman224   File: Bubble_Sort.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
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 37
Project: LeetCode   Author: jiadaizhao   File: 0791-Custom Sort String.cpp    License: MIT License 6 votes vote down vote up
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 38
Project: CppLearingArchive   Author: ErdemOzgen   File: ex_1906.cpp    License: MIT License 6 votes vote down vote up
void bubbleSort(std::vector<int>& intVec) {
    size_t size = intVec.size();
    bool swap = false;

    for (size_t i = 0; i < size - 1; swap = false, ++i) {
        for (size_t j = 0; j < size - i - 1; ++j) {
            // reverse comparison for reverse ordered sorting
            if (intVec[j] > intVec[j + 1]) {
                int tmp = intVec[j];

                intVec[j] = intVec[j + 1];
                intVec[j + 1] = tmp;

                swap = true;
            }
        }
        if (!swap) { break; }
    }
} 
Example 39
Project: Hacktoberfest   Author: shivaylamba   File: heapsort.cpp    License: MIT License 6 votes vote down vote up
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 40
Project: inviwo   Author: inviwo   File: processordraghelper.cpp    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
filterAndSortOutports(Iter begin, Iter end, dvec2 pos, Pred pred) {

    end = std::partition(begin, end, [&](Outport* p) {
        return static_cast<double>(util::getPosition(p->getProcessor()).y) +
                       ProcessorGraphicsItem::size_.height() <
                   pos.y &&
               pred(p);
    });

    std::sort(begin, end, [&](Outport* p1, Outport* p2) {
        // weight horizontal distance 3 times over vertical distance
        auto d1 =
            glm::length2(dvec2(3.0, 1.0) * (pos - dvec2(util::getPosition(p1->getProcessor()))));
        auto d2 =
            glm::length2(dvec2(3.0, 1.0) * (pos - dvec2(util::getPosition(p2->getProcessor()))));
        return d1 < d2;
    });
    return {begin, end};
} 
Example 41
Project: Programmers-Community   Author: shoaibrayeen   File: SolutionByIshaKansal.cpp    License: MIT License 6 votes vote down vote up
void sort_012(vector <int>&arr)
{
int pt1=0,itr=0,pt2=arr.size()-1;
//pt1 makes sure all elements before it are 0
//pt2 makes sure all elements after it are 2 
//itr traverses entire array
while(itr<=pt2)
{
if(arr[itr]==0)
{
    swap(arr[pt1],arr[itr]);
   pt1++;
   itr++;
}
else if(arr[itr]==2)
{
    swap(arr[pt2],arr[itr]);
    pt2--;
}
else 
Example 42
Project: CppLearingArchive   Author: ErdemOzgen   File: ex_731.cpp    License: MIT License 6 votes vote down vote up
void selectionSort(int n[], int LIMIT) {
    static int startIndex = 0;
    int minIndex = startIndex;

    // exit condition
    if (startIndex >= LIMIT - 1) { return; }

    // get the index of the smallest value
    for (int i = startIndex + 1; i < LIMIT; ++i) {
        if (n[i] < n[minIndex]) { minIndex = i; }
    }

    // swap with n[startIndex]
    int tmp = n[startIndex];
    n[startIndex] = n[minIndex];
    n[minIndex] = tmp;

    // increment startIndex
    ++startIndex;

    selectionSort(n, LIMIT);
} 
Example 43
Project: cosmos   Author: OpenGenus   File: sjf.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
void sort_arrival_time(int arrival_time[],int process[],int burst_time[])
// Function is used to sort the processes on the basis of their arrival time.
// In case, two processes have same arrival time they will be placed next to each other.
{
  for(int i=0;i<4;i++)
  {
    for(int j=i+1;j<4;j++)
    {
      if(arrival_time[i]>arrival_time[j])
      {
        swap(process[i],process[j]);
        swap(arrival_time[i],arrival_time[j]);
        swap(burst_time[i],burst_time[j]);
        // Process id, arrival time as well as burst time of the processes are sorted inaccordance with arrival time.
      }
    }
  }
} 
Example 44
Project: gmark   Author: gbagan   File: correlation.cpp    License: MIT License 6 votes vote down vote up
vector<int> incrementalDeterministicGraphGenerator::sortOnDegree(vector<int> objectsIterationIds) {
	vector<pair<int,int> > degreeIteratioIdPairs;
	for (int i: objectsIterationIds) {
		int degree = nodes.second[i].numberOfInterfaceConnections;
		degreeIteratioIdPairs.push_back(make_pair(degree, i));
	}
	sort(degreeIteratioIdPairs.begin(), degreeIteratioIdPairs.end(), pairCompare);

//	cout << "Sorted on degree: ";
	vector<int> sortedObjectIds;
	for (pair<int,int> degreeIdPair: degreeIteratioIdPairs) {
//		cout << "(" << degreeIdPair.first << "," << degreeIdPair.second << "), ";
		sortedObjectIds.push_back(degreeIdPair.second);
	}
//	cout << endl;
	return sortedObjectIds;
} 
Example 45
Project: quark   Author: OpenGenus   File: bubble_sort.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
void
bubbleSort(_Bidirectional_Iter begin, _Bidirectional_Iter end, _Compare compare)
{
    if (begin != end)
    {
        auto frontOfSorted = end;

        for (--frontOfSorted; frontOfSorted != begin; --frontOfSorted)
        {
            bool swapped{};
            for (auto j = begin; j != frontOfSorted; ++j)
            {
                auto nextOfJ = j;
                if (compare(*++nextOfJ, *j))
                {
                    std::iter_swap(nextOfJ, j);
                    swapped = true;
                }
            }
            if (swapped == false)
                break;
        }
    }
} 
Example 46
Project: orbit   Author: google   File: SessionsDataView.cpp    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
void PresetsDataView::DoSort() {
  bool ascending = m_SortingOrders[m_SortingColumn] == SortingOrder::Ascending;
  std::function<bool(int a, int b)> sorter = nullptr;

  switch (m_SortingColumn) {
    case COLUMN_SESSION_NAME:
      sorter = ORBIT_PRESET_SORT(m_FileName);
      break;
    case COLUMN_PROCESS_NAME:
      sorter = ORBIT_PRESET_SORT(m_ProcessFullPath);
      break;
    default:
      break;
  }

  if (sorter) {
    std::stable_sort(m_Indices.begin(), m_Indices.end(), sorter);
  }
} 
Example 47
Project: vnote   Author: tamlok   File: vlistfolderue.cpp    License: MIT License 6 votes vote down vote up
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 48
Project: algo4j   Author: ice1000   File: merge_sort_test.cpp    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
void merge_sort_recursive(T arr[], T reg[], int start, int end) {
	if (start >= end)
		return;
	int len = end - start, mid = (len >> 1) + start;
	int start1 = start, end1 = mid;
	int start2 = mid + 1, end2 = end;
	merge_sort_recursive(arr, reg, start1, end1);
	merge_sort_recursive(arr, reg, start2, end2);
	int k = start;
	while (start1 <= end1 && start2 <= end2)
		reg[k++] = arr[start1] < arr[start2] ? arr[start1++] : arr[start2++];
	while (start1 <= end1)
		reg[k++] = arr[start1++];
	while (start2 <= end2)
		reg[k++] = arr[start2++];
	for (k = start; k <= end; k++)
		arr[k] = reg[k];
} 
Example 49
Project: bmc64   Author: randyrossi   File: comprlib.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
void HuffmanNode::sortNodes(HuffmanNode *startPtr, HuffmanNode *endPtr,
                              HuffmanNode *tmpBuf)
  {
    size_t  n = size_t(endPtr - startPtr);
    if (n < 2)
      return;
    size_t  m = n >> 1;
    if (m > 1)
      sortNodes(startPtr, startPtr + m, tmpBuf);
    if ((n - m) > 1)
      sortNodes(startPtr + m, endPtr, tmpBuf);
    size_t  i = 0;
    size_t  j = m;
    for (size_t k = 0; k < n; k++) {
      if (PLUS4EMU_UNLIKELY(j >= n))
        tmpBuf[k].nodeData = startPtr[i++].nodeData;
      else if (PLUS4EMU_UNLIKELY(i >= m) || startPtr[j] < startPtr[i])
        tmpBuf[k].nodeData = startPtr[j++].nodeData;
      else 
Example 50
Project: Algorithms   Author: steveLauwh   File: IndexMaxHeap.cpp    License: Apache License 2.0 6 votes vote down vote up
void heapSort(T arr[], int n)
{
    IndexMaxHeap<T> indexMaxHeap = IndexMaxHeap<T>(n);
    
    for (int i = 0; i < n; i++)
    {
        indexMaxHeap.insert(i, arr[i]);
    }
  
    indexMaxHeap.change(5, 88);
  
    for (int i = n - 1; i >= 0; i--)
    {
        arr[i] = indexMaxHeap.extractMax();
    }
} 
Example 51
Project: cosmos   Author: OpenGenus   File: bubble_sort.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
void
bubbleSort(_Bidirectional_Iter begin, _Bidirectional_Iter end, _Compare compare)
{
    if (begin != end)
    {
        auto frontOfSorted = end;

        for (--frontOfSorted; frontOfSorted != begin; --frontOfSorted)
        {
            bool swapped{};
            for (auto j = begin; j != frontOfSorted; ++j)
            {
                auto nextOfJ = j;
                if (compare(*++nextOfJ, *j))
                {
                    std::iter_swap(nextOfJ, j);
                    swapped = true;
                }
            }
            if (swapped == false)
                break;
        }
    }
} 
Example 52
Project: Algorithms   Author: steveLauwh   File: SortColors.cpp    License: Apache License 2.0 6 votes vote down vote up
void sortColors(vector<int>& nums) {
        int colors[3] = {0};
        
        int count = nums.size();
        
        // 计数
        for (int i = 0; i < count; i++) {
            colors[nums[i]] ++;
        }
        
        int index = 0;
        for (int i = 0; i < colors[0]; i++) {
            nums[index++] = 0;
        }
        
        for (int i = 0; i < colors[1]; i++) {
            nums[index++] = 1;
        }
        
        for (int i = 0; i < colors[2]; i++) {
            nums[index++] = 2;
        }
    } 
Example 53
Project: cosmos   Author: OpenGenus   File: insertion_sort.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
void
insertionSort(_Bidirectional_Iter begin, _Bidirectional_Iter end, _Compare compare)
{
    if (begin != end)
    {
        auto backOfBegin = begin;
        --backOfBegin;

        auto curr = begin;
        for (++curr; curr != end; ++curr)
        {
            auto pivot = *curr;
            auto backward = curr;
            auto nextOfBackward = curr;
            while (--backward != backOfBegin && compare(pivot, *backward))
            {
                *nextOfBackward = *backward;
                --nextOfBackward;
            }
            *nextOfBackward = pivot;
        }
    }
} 
Example 54
Project: quark   Author: OpenGenus   File: counting_sort.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
void countingSort(vector<int> arr,vector<int>& sortedA){
	int m=INT_MIN;
	for(int i=0;i<arr.size();i++){
		if(arr[i]>m){
			m=arr[i];
		}
	}
	int freq[m+1]; //m is the maximum number in the array
	for(int i=0;i<=m;i++)
		freq[i]=0;
	for(int i=0;i<arr.size();i++)
		freq[arr[i]]++;
	int j = 0;
    for(int i=0;i<=m;i++){
        int tmp=freq[i];
        while(tmp--){
            sortedA[j] = i;
            j++;
        }
    }
} 
Example 55
Project: C-Plus-Plus   Author: TheAlgorithms   File: bucket_sort.cpp    License: MIT License 6 votes vote down vote up
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 56
Project: algorithms-in-C-Cplusplus-Java-Python-JavaScript   Author: kinetickansra   File: exchange_sort.cpp    License: MIT License 6 votes vote down vote up
int exchange_sort(int arr[],int n)
{
	int i, j;
	int tmp;

	for(i=0;i<n-1;i++)
	{
		for (j=i+1;j<n;j++)
		{
			if (arr[i]>arr[j])
			{
				tmp = arr[i];
				arr[i] = arr[j];
				arr[j] = tmp;
			}
			
			return arr[i];
		}/*end of inner j for loop*/
	}/*end of outer i for loop*/
} 
Example 57
Project: HackerRank   Author: MrinmoiHossain   File: Quicksort2-Sorting.cpp    License: MIT License 6 votes vote down vote up
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 58
Project: Hacktoberfest   Author: shivaylamba   File: Insertion_sort.cpp    License: MIT License 6 votes vote down vote up
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 59
Project: cosmos   Author: OpenGenus   File: randomized_quicksort.c    License: GNU General Public License v3.0 6 votes vote down vote up
void quick_sort(int arr[], int p, int q)

    {

        int j;

        if (p < q)

        {

            j = partion(arr, p, q);

            quick_sort(arr, p, j-1);

            quick_sort(arr, j+1, q);

        }

    } 
Example 60
Project: nCine   Author: nCine   File: Material.cpp    License: MIT License 6 votes vote down vote up
uint32_t Material::sortKey()
{
	uint16_t lower = 0;
	uint32_t middle = 0;
	uint32_t upper = 0;

	if (texture_)
		lower = static_cast<uint16_t>(texture_->glHandle());

	if (shaderProgram_)
		middle = shaderProgram_->glHandle() << 16;

	if (isBlendingEnabled_)
	{
		upper = glBlendingFactorToInt(srcBlendingFactor_) * 16 + glBlendingFactorToInt(destBlendingFactor_);
		upper = upper << 24;
	}

	return upper + middle + lower;
}