Reputation: 23
How do use vector or in-built sort function in C++ with most of the language in C? I am trying to just sort an array for a C program. Can it explained with a simple code with sort implementation? I am very new to C++.
Upvotes: 0
Views: 9507
Reputation: 1
This method used built in sorting algorithm and changes its time complexity based on the input array.
1. #include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
int n = sizeof(arr)/sizeof(arr[0]);
sort(arr, arr+n); //sort(arr, arr+n, greater<int>()); for descending
cout << "\nArray after sorting
using "
"default sort is : \n";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
Upvotes: -1
Reputation: 7802
Here is a qsort example for sorting strings that sorts and prints the passed arguments:
#include <string.h>
static inline int cmp(const void *a, const void *b){
return strcmp(*(const char **)a, *(const char **)b);
}
int main(int argc, char *argv[]){
qsort(++argv, --argc, sizeof(char *), cmp);
while (argc){
write(1,argv[0],strlen(argv[0]));
write(1,(--argc && argv++)?"\t":"\n",1);
}
}
for other types just replace the strcmp with a-b in the cmp() function and swap the order to change ascending vs. descending.
Upvotes: 0