C++STLソート関数

3120 ワード

C++の書き方:
sortとstableソートは元の配列、STL容器に並べ替えられます。そしてrtは快速で並べられます。不安定で、stable_ソトは規格を採用して並べ替えて実現して、安定して、時間の複雑さは皆N*log(N)です。
//    
//sort stable_sort  
//     void sort(_RanIt _First, _RanIt _Last, _Pr _Pred)
//   http://www.cplusplus.com/reference/algorithm/sort/
#include 
#include 
#include 
#include 

using namespace std;


template 
void Print (vector array)
{
  int size = array.size();
  cout << "size: " << size << endl;
  for (int i = 0; i < size; ++i)
  {
    cout << array[i] << endl;
  }
}

bool CompIntLess(int first,int second)
{
  return (first) < (second);
}

bool CompIntGreater(int first,int second)
{
  return (first) > (second);
}

void SortInt()
{
  vector array;
  array.push_back(4);
  array.push_back(5);
  array.push_back(1);
  array.push_back(2);

  //  
  cout << "sort with from small to big" << endl;
  sort(array.begin(),array.end(),less());
  Print(array);
  cout << "sort with from big to small" << endl;
  sort(array.begin(),array.end(),greater());
  Print(array);

  //    
  cout << "sort with from small to big" << endl;
  stable_sort(array.begin(),array.end(),less());
  Print(array);
  cout << "sort with from big to small" << endl;
  stable_sort(array.begin(),array.end(),greater());
  Print(array);

  //  compare    
  cout << "sort with from small to big" << endl;
  sort(array.begin(),array.end(),CompIntLess);
  Print(array);
  cout << "sort with from big to small" << endl;
  sort(array.begin(),array.end(),CompIntGreater);
  Print(array);
}

void SortIntArray()
{
  int a[10] = {5, 6, 4, 3, 7, 0 ,8, 9, 2, 1};

  cout << "sort with from small to big" << endl;
  sort(a, a + 10, less());
  for (int i = 0; i < 10; i++)
    cout << a[i] << " " << endl;
  cout << "sort with from big to small" << endl;
  sort(a, a + 10, greater());
  for (int i = 0; i < 10; i++)
    cout << a[i] << " " << endl;
}

int main(){
  SortInt();
  SortIntArray();

  int ttt = 0;

  return 0;
}
Cの書き方:
qsortは元の配列にしか並べられません。STL容器に並べ替えられません。
//    
//qsort  
//     void qsort(void * _Base, int _NumOfElements, int _SizeOfElements, int (* _PtFuncCompare)(const void *, const void *));
//   http://www.cplusplus.com/reference/cstdlib/qsort/
#include 
#include 

using namespace std;

int compare(const void *a, const void *b)
{
  int *pa = (int*)a;
  int *pb = (int*)b;
  return (*pa) - (*pb);  //      
}

void main()
{
  int a[10] = {5, 6, 4, 3, 7, 0 ,8, 9, 2, 1};
  qsort(a, 10, sizeof(int), compare);
  for (int i = 0; i < 10; i++)
    cout << a[i] << " " << endl;

  int ttt = 0;
}