How to use std::sort to sort an array in C++

C++Sorting

C++ Problem Overview


How to use standard template library std::sort() to sort an array declared as int v[2000];

Does C++ provide some function that can get the begin and end index of an array?

C++ Solutions


Solution 1 - C++

In C++0x/11 we get std::begin and std::end which are overloaded for arrays:

#include <algorithm>

int main(){
  int v[2000];
  std::sort(std::begin(v), std::end(v));
}

If you don't have access to C++0x, it isn't hard to write them yourself:

// for container with nested typedefs, non-const version
template<class Cont>
typename Cont::iterator begin(Cont& c){
  return c.begin();
}

template<class Cont>
typename Cont::iterator end(Cont& c){
  return c.end();
}

// const version
template<class Cont>
typename Cont::const_iterator begin(Cont const& c){
  return c.begin();
}

template<class Cont>
typename Cont::const_iterator end(Cont const& c){
  return c.end();
}

// overloads for C style arrays
template<class T, std::size_t N>
T* begin(T (&arr)[N]){
  return &arr[0];
}

template<class T, std::size_t N>
T* end(T (&arr)[N]){
  return arr + N;
}

Solution 2 - C++

#include <algorithm>
static const size_t v_size = 2000;
int v[v_size];
// Fill the array by values
std::sort(v,v+v_size); 

In C++11:

#include <algorithm>
#include <array>
std::array<int, 2000> v;
// Fill the array by values
std::sort(v.begin(),v.end()); 

Solution 3 - C++

If you don't know the size, you can use:

std::sort(v, v + sizeof v / sizeof v[0]);

Even if you do know the size, it's a good idea to code it this way as it will reduce the possibility of a bug if the array size is changed later.

Solution 4 - C++

You can sort it std::sort(v, v + 2000)

Solution 5 - C++

//It is working
#include<iostream>
using namespace std;
void main()
{
	int a[5];
	int temp=0;
	cout<<"Enter Values"<<endl;
	for(int i=0;i<5;i++)
	{
		cin>>a[i];
	}
	for(int i=0;i<5;i++)
	{
		for(int j=0;j<5;j++)
		{
			if(a[i]>a[j])
			{
				temp=a[i];
				a[i]=a[j];
				a[j]=temp;
			}
		}
	}
	cout<<"Asending Series"<<endl;
	for(int i=0;i<5;i++)
	{
		cout<<endl;
		cout<<a[i]<<endl;
	}


	for(int i=0;i<5;i++)
	{
		for(int j=0;j<5;j++)
		{
			if(a[i]<a[j])
			{
				temp=a[i];
				a[i]=a[j];
				a[j]=temp;
			}
		}
	}
	cout<<"Desnding Series"<<endl;
	for(int i=0;i<5;i++)
	{
		cout<<endl;
		cout<<a[i]<<endl;
	}


}

Solution 6 - C++

you can use sort() in C++ STL. sort() function Syntax :

 sort(array_name, array_name+size)      

 So you use  sort(v, v+2000);

Solution 7 - C++

It is as simple as that ... C++ is providing you a function in STL (Standard Template Library) called sort which runs 20% to 50% faster than the hand-coded quick-sort.

Here is the sample code for it's usage:

std::sort(arr, arr + size);

Solution 8 - C++

//sort by number
bool sortByStartNumber(Player &p1, Player &p2) {
	return p1.getStartNumber() < p2.getStartNumber();
}
//sort by string
bool sortByName(Player &p1, Player &p2) {
	string s1 = p1.getFullName();
	string s2 = p2.getFullName();
	return s1.compare(s2) == -1;
}

Solution 9 - C++

With the Ranges library that is coming in C++20, you can use

ranges::sort(arr);

directly, where arr is a builtin array.

Solution 10 - C++

sorting method without std::sort:

// sorting myArray ascending
int iTemp = 0;
for (int i = 0; i < ARRAYSIZE; i++)
{
    for (int j = i + 1; j <= ARRAYSIZE; j++)
    {
        // for descending sort change '<' with '>'
        if (myArray[j] < myArray[i])
        {
            iTemp = myArray[i];
            myArray[i] = myArray[j];
            myArray[j] = iTemp;
        }
    }
}

Run complete example:

#include <iostream> // std::cout, std::endl /* http://en.cppreference.com/w/cpp/header/iostream */
#include <cstdlib>  // srand(), rand()      /* http://en.cppreference.com/w/cpp/header/cstdlib */
#include <ctime>    // time()               /* http://en.cppreference.com/w/cpp/header/ctime */


int main()
{
    const int ARRAYSIZE = 10;
    int myArray[ARRAYSIZE];

    // populate myArray with random numbers from 1 to 1000
    srand(time(0));
    for (int i = 0; i < ARRAYSIZE; i++)
    {
        myArray[i] = rand()% 1000 + 1;
    }

    // print unsorted myArray
    std::cout << "unsorted myArray: " << std::endl;
    for (int i = 0; i < ARRAYSIZE; i++)
    {
        std::cout << "[" << i << "] -> " << myArray[i] << std::endl;
    }
    std::cout << std::endl;

    // sorting myArray ascending
    int iTemp = 0;
    for (int i = 0; i < ARRAYSIZE; i++)
    {
        for (int j = i + 1; j <= ARRAYSIZE; j++)
        {
            // for descending sort change '<' with '>'
            if (myArray[j] < myArray[i])
            {
                iTemp = myArray[i];
                myArray[i] = myArray[j];
                myArray[j] = iTemp;
            }
        }
    }

    // print sorted myArray
    std::cout << "sorted myArray: " << std::endl;
    for (int i = 0; i < ARRAYSIZE; i++)
    {
        std::cout << "[" << i << "] -> " << myArray[i] << std::endl;
    }
    std::cout << std::endl;

    return 0;
}

Solution 11 - C++

Use the C++ std::sort function:

#include <algorithm>
using namespace std;

int main()
{
  vector<int> v(2000);
  sort(v.begin(), v.end());
}

Solution 12 - C++

C++ sorting using sort function

#include <bits/stdc++.h>
 using namespace std;

vector <int> v[100];

int main()
{
  sort(v.begin(), v.end());
}

Solution 13 - C++

you can use,

 std::sort(v.begin(),v.end());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser707549View Question on Stackoverflow
Solution 1 - C++XeoView Answer on Stackoverflow
Solution 2 - C++NasztaView Answer on Stackoverflow
Solution 3 - C++j_random_hackerView Answer on Stackoverflow
Solution 4 - C++MayankView Answer on Stackoverflow
Solution 5 - C++wahid ButtView Answer on Stackoverflow
Solution 6 - C++rashedcsView Answer on Stackoverflow
Solution 7 - C++risheek reddyView Answer on Stackoverflow
Solution 8 - C++user5465465465View Answer on Stackoverflow
Solution 9 - C++L. F.View Answer on Stackoverflow
Solution 10 - C++user6021501View Answer on Stackoverflow
Solution 11 - C++user7069426View Answer on Stackoverflow
Solution 12 - C++Mahedi Hasan DurjoyView Answer on Stackoverflow
Solution 13 - C++Rohit HajareView Answer on Stackoverflow