Добавил:
Upload
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:05. Функции / Examples / 09_functions_as_parameters / 09_qsort
.cpp#include <iostream>
using namespace std;
// Две функции-компаратора для сравнения переменных типа int
int intCmp(const void * pa, const void *pb)
{
const int* a = reinterpret_cast<const int*>(pa);
const int* b = reinterpret_cast<const int*>(pb);
return *a - *b;
}
int intCmpReverse(const void * pa, const void *pb)
{
const int* a = reinterpret_cast<const int*>(pa);
const int* b = reinterpret_cast<const int*>(pb);
return -(*a - *b);
}
int main()
{
int a[10] = {2, -3, 3, 4, 8, 9, 3, 1, 7, 6};
// Сортировка массива по возрастанию
qsort(a, 10, sizeof(int), intCmpReverse);
for (int i=0; i<10; ++i)
cout << a[i] << ' ';
cout << endl;
// сортировка массива по убыванию
qsort(a, 10, sizeof(int), intCmpReverse);
for (int i=0; i<10; ++i)
cout << a[i] << ' ';
cout << endl;
}