Saturday 7 July 2018

sort and binary search in C++


int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    sort(arr, arr+n); //
0 1 2 3 4 5 6 7 8 9
sort in descending order?
sort(arr, arr+n, greater<int>()); //
9 8 7 6 5 4 3 2 1 0
sort in particular order?

// A C++ program to demonstrate STL sort() using
// our own comparator
#include
using namespace std;
 
// An interval has start time and end time
struct Interval
{
    int start, end;
};
 
// Compares two intervals according to staring times.
bool compareInterval(Interval i1, Interval i2)
{
    return (i1.start < i2.start);
}
 
int main()
{
    Interval arr[] =  { {6,8}, {1,9}, {2,4}, {4,7} };
    int n = sizeof(arr)/sizeof(arr[0]);
 
    // sort the intervals in increasing order of
    // start time
    sort(arr, arr+n, compareInterval);
 
    cout << "Intervals sorted by start time : \n";
    for (int i=0; i
       cout << "[" << arr[i].start << "," << arr[i].end
            << "] ";
 
    return 0;
}
Intervals sorted by start time : 
[1,9] [2,4] [4,7] [6,8]
------------

This searching only works when container is sorted.

 vector<int> arr = {10, 15, 20, 25, 30, 35};
     
    // using binary_search to check if 15 exists
    if (binary_search(arr.begin(), arr.end(), 15))
       cout << "15 exists in vector";
    else
       cout << "15 does not exist";
      




No comments:

Post a Comment