ashrithhcs
ashrithhcs

Reputation: 23

In-built Sorting in C++

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

Answers (4)

prateek54
prateek54

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

technosaurus
technosaurus

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

Caesar
Caesar

Reputation: 9841

If you want to sort in C then you should use qsort.

If you want to sort in C++ then you should use std::sort

Upvotes: 5

A.B.
A.B.

Reputation: 16630

std::sort has a code example:

std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; 

// sort using the default operator<
std::sort(s.begin(), s.end());
for (int a : s) {
    std::cout << a << " ";
}   
std::cout << '\n';

Output:

0 1 2 3 4 5 6 7 8 9

Upvotes: 3

Related Questions