Longest Alternating Subarray is a problem of finding a subarray with alternating positive and negative elements, and in which the subarray is as long as possible.
The problem differs from problem of finding Longest Alternating Subsequence, unlike a subsequence, subarray is required to occupy consecutive positions within the original sequences.
For example, consider array { 1, 12, 6, 4, -3, 2, -4,-3. The longest alternating subarray is ( 4, -3, 2, -4) Note that the longest alternating subarray might not be unique
We can easily solve this problem in linear time using similar logic as Kidane's algorithm. The idea to maintain the longest alternating sub-array "ending" at each index of the given array. This subarray can be a single element of a previous element has the same sign) or consists of one more elemments than the longest alternating subarray ending at the previous index (if the previous element has the opposite sign
We are going to discuss of top 3 programming language that can help you in landing a good job in the idustry.There exist more programming languages than the human language in the world. The need and prevalence of programming languages vary each year. Also, modern programming languages are arising from engaging characteristics.
So, which programming language's knowledge should you acquire to get a good job in 2020? Studying a modern programming language is invariably an expenditure of your time and mind. If you are a mature coder or if you already know some programming languages, then you can learn a new improved one.
If you are beginning your programming journey in 2020 or if you require to discover your primary or secondary programming language, then it is smart to acquire knowledge of one of the trending and practiced programming languages. Here I will classify programming languages based on the subsequent measures:
They are in high demand in the job market with a higher salary and perks.
Top-ranked in the notable programming languages on different listing websites and blogs.
Demand is rising or steady and not going out of the market soon.
They have a huge collection of libraries, frameworks, hardware integration, tooling support, and have a wide community.
Already trending and heavily practiced in the Software Development enterprise.
In 2020 various programming languages become less important and new programming languages have emerged. A general rule in the world is everything keeps changing with time and the same applies to programming languages too. To be more relevant in the industry you have to adopt the latest technology and practices. So without any further discussion, we are starting our list of the top 3 programming languages to learn to get a good job in 2020.
1. Python
Python is one of the most popular programming languages in the universe right now. This language is generally trusted by data scientists, data analysts, and ML experts around the world. It has also gained a lot of popularities in the software industry hence ve software engineers, software developers web developers s and many people related to the software industry using it as a good tool. that is the reason for being number in the top 3 programming languages.
Historyof python
Python was established in the late 1980s The work on Python was started in December 1989 by Guido Van Rossum at CWI in Netherland. In February 1991, Guido Van Rossum distributed the code (labeled version 0.9.0) to alt. sources. in 1994, Python 1.0 was released with new innovations like lambda, map, filter, and reduce.
Features of python
It is a beginner-friendly language. A person from a non-coding background can learn and adapt to this programming language very easily.
The major advantage of Python is its language design. It is highly productive, elegant, simple, and more powerful.
Python has a very large and active community and support for its user.
It is an open-source programming language that implies that anyone can design and contribute to its expansion.
Python has been created to be a high-level programming language. This implies that when you code in Python you have not required to be aware of the code arrangement, the structure also memory management.
There is a large number of libraries and frameworks that are built for the python and help users ease to work.
Python has topless integration with C and C++ and can seamlessly load and unload the CPU obscure tasks to C/C++ to save time and stress.
Popularity and current trend
In the last several years, Python has seen tremendous growth in demand with no clue of quieting down. I In 2019 Python has surpassed Java and became the 2nd most popular language. The programming language ranking site PYPL has ranked Python as the number one programming language with a sizable popularity addition in 2020 and most probably in the next 5-10 years python is going to dominate the market.
The job market of python
According to Indeed, Python is the most demanding programming language in the USA job market with around 80 K jobs in September 2020. Also, Python ranked third with a $118 K yearly salary and predication has been made it will grow much faster in the upcoming decade.
StackOverflow developer poll has revealed that Python developers make a high salary with comparatively inferior exposure related to other top programming languages. according to different surveys, python is one of the must skills required for a software development job roles. That is the reason for mentioning at position 1 in Top 3 Programming Languages learn to get a good job in 2020.
Uses of python
Data Science
Machine Learning
Game Development
GUI development
Scripting
Data scrapping
Data Analytics and big data
Artificial Intelligence and Deep Learning
Enterprise-level Application
Web Development and deployment
2. Java
Java is one of the most used programming languages till now. It is a programming language that builds software for various stages. When a programmer records a Java application, the compiled code (identified as bytecode) works on most operating systems including Windows, Linux, and Mac OS, and many more. Java obtains much of its syntax from the C and C++ programming languages.
It has managed Platform freedom by generating Java Virtual Machine (JVM), which separated the low-level Operating System and machine code from developers/coders and delivered the simple code that can be run on any OS without worrying about machine code. JVM offered contemporaries garbage collection, which operates the Object life cycle in your code.
History of java
The origins of creating Java programming were Simple, Robust, Portable, Platform-independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic. It was produced by James Gosling, who is recognized as the creator of Java, in 1995. James Gosling and his team members started the project in the early '90s. Firstly, it was called Green talk by James Gosling, and the file extension was .gt. After that, it was called Oak and was developed as a part of the Green project.
Features of Java
Java is very simple to get, and its syntax is manageable, reliable, and simple to follow.
It is an object-oriented programming language. Everything in Java is an object.
It is platform-independent because it is distinct from other languages like C, C++, etc. which are compiled into platform-specific machines while Java is a write once, run everywhere language.
Java is famously recognized for its safety. With Java, we can produce virus-free systems.
It is surely backward cooperative, which is a fundamental necessity for enterprise software.
Java is architecture-neutral because there are no implementation-dependent characteristics.
It is portable because it helps you to take the Java bytecode to any platform.
Java supports multithreading. It is beneficial for system-level development.
Popularity and current trend
Just subsequent five years of its release, it grows the third most prevalent programming language and constantly settled in the best three listings in the subsequent two decades.
Each year, StackOverflow publishes its Developer Survey for tech aficionados all throughout the globe. Looking backward at the results from 2019 and earlier years, the whole idea is clear – it is forever a Top 5 Most Popular Technology in the and will remain because of it's vast support to the enterprise applications.
According to the tardiest TIOBE 2020 Popularity Index, it is the most prevalent language used by developers over various corners of the globe. If you are curious to learn Java, you would be fascinated to understand that it has the most number of submissions on any competitive programming website in the entire globe. Java is the undergraduate student's most favorable programming language.
A lot of new technology and programming language are coming into the market. Java’s fame has faded in the closing few years. According to Google trends, it is dropping its friction steadily in the past five years.
The job market of Java
According to Indeed, it is the second most demanding programming language after python in the USA job market with around 75 K jobs in September 2020. Also, Python ranked fourth with a $104 K yearly salary and predication has been made it will grow much faster in the upcoming years.
Uses of Java
Mobile Applications
Desktop GUI Applications
Web-based Applications
Enterprise Applications
Scientific Applications
Gaming Applications
Big Data technologies
Business Applications
Distributed Applications
Cloud-based Applications
3.C++
C++ is a general-purpose programming language that was developed as an improvement of the C language to include an object-oriented model. It is a powerful and compiled language. Thoroughly inspired by C. Over time, C++ has emerged into a multi-paradigm, general-purpose programming language. Like C, C++ also offers low-level memory passage and instantly compiled to machine instructions.
History of C++
C++ programming language was developed in 1980 by Bjarne Stroustrup at bell laboratories of AT&T (American Telephone & Telegraph), located in the U.S.A. Bjarne Stroustrup is acknowledged as the founder of the C++ language. It was originally remembered as C with classes and was renamed C++ in 1983. C++ is shorthand for adding one to change in programming, .therefore C++ roughly means that one higher than C. Now days is C++ is more than just c with classes with the huge support of external libraries.
Features of C++
Object-Oriented Programming language
C++ is simple and easy to learn programming language
It is a platform Dependent language that means you have to compile your code on each system.
C++ has efficiently like low-level language and ease to use like high-level language and yes it is a Mid-level programming language
It is a Structured programming language like C.
C++ has rich Library support from a third party and C++ itself (Boost, STL, MLpack ...)
You can utilize memory and processor Efficiently using C++.
C++ is Powerful & Fast
It has Support of Pointers.
C++ also allows full administration across the hardware.
Compiler based language.
Syntax based language.
Popularity and current trend
C++ is one of the oldest programming languages in the world and still in practice. It is the powerer and flexibility of programming language that is granted to the user. StackOverflow Developer Survey in 2019 has placed C++ as the 9th most prominent Technology and 6th most prevalent language in the globe.
The increasing prevalence of Python had sidelines C++ over the aftermost few years. The programming language is back among top positions on TIOBE's September 2020 index. TIOBE has given a rating of 7.11% to C++, recording a 1.48% increase over September 2019.
It seems C++ gaining its popularity back. C++ is also my favorite language and you can say I biased towards C++, yeah it's true just because of its flexibility and ease to use.
The job market of C++
According to Indeed, C++ is the fourth most demanding programming language after python java, and javascript. In the USA job market with around 50 K jobs in September 2020. Also, C++ ranked 5th with a $104 K yearly salary and predication has been made it will grow much faster than any programming language in the upcoming years. Stackoverflow survey tells us that an experienced C++ developer earns more than Java and Python developers in long run. We have added C++ to our top 3 programming languages list just because of it's high paying salary.
There are a lot of career opportunity as a C++ developer you can see the career opportunity of C++ developers here in Uses of C++
Uses of C++
OperatingSystems
Browsers
Programming the graphics processor
Making Frameworks and libraries for different programming language.
Making games and apps for system and mobile
Cross platform development
Game Engine development
Database development
Embedded system programing.
Making compilers.
Here is the list of the top 3 programming languages learn to get a good job in 2020.
We are going to use a predefined function that has been described in STL algorithms this function is sort(). Using this function we will get our output.
Syntax
sort(vec.begin(), vec.end())
Implementation :
#include<iostream> #include<vector> #include <algorithm> int main() { // INtialize and store the vector std::vector<int> vec = {12, 35, 44, 54, 23, 24, 87}; // We need to sort the vector the vector in ascending order std::sort(vec.begin(), vec.end(),greater<int>()); // Printout the sorted vector std::cout << "Sorted Vector : "; for (int i = 0; i < vec.size(); i++) { std::cout << vec1.at(i) << " "; } std::cout << std::endl; return 0; }
We are going to use a predefined function that has been described in STL algorithms this function is sort(). Using this function we will get our output.
Syntax
sort(vec.begin(), vec.end() , greater<T>());
//here T is the data type { ex: int, float, double ..
What is the use of greater<T>() :
This is a predefined function inside the STL library who resembles two elements while sorting and return greater element first. This is the logic for applying greater<T>() for sorting the vector in descending order.
Implementation :
#include<iostream> #include<vector> #include <algorithm> int main() { // INtialize and store the vector std::vector<int> vec = {12, 35, 44, 54, 23, 24, 87}; // We need to sort the vector the vector in descending order std::sort(vec.begin(), vec.end(),greater<int>()); // Printout the sorted vector std::cout << "Sorted Vector : "; for (int i = 0; i < vec.size(); i++) { std::cout << vec1.at(i) << " "; } std::cout << std::endl; return 0; }
In this article, we will be discussing how to obtain shared elements between two vectors using STL in C++. To find this we are not writing any algorithm. We have methods defined STL library under algorithm does this stuff.
We are going to use predefined function that has been described in STL algorithms this function is set_intersection() . Using this function we will get our output.
Syntax :
auto lastPointer = std::set_intersection (vector1->start, vector1->end,vector2->start, vector2->end, outpur vector->Start);
Implementation :
#include<iostream> #include<vector> #include <algorithm> int main() { // INtialize and store the vector std::vector<int> vec1 = { 1, 24, 54, 71, 76, 12 }; std::vector<int> vec2 = {12, 27, 65, 76, 26, 24}; // We need to sort the vector to find the interaction point with //this perticular algorithm std::sort(vec1.begin(), vec1.end()); std::sort(vec2.begin(), vec2.end()); // Printout the vector vec1 and vec 2 std::cout << "Vec1 : "; for (int i = 0; i < vec1.size(); i++) std::cout << vec1.at(i) << " "; std::cout << std::endl; std::cout << "Vec2 : "; for (int i = 0; i < vec2.size(); i++) std::cout << vec2.at(i) << " "; std::cout << std::endl; // Initialise the output vector with size of vec1+vec2; std::vector<int> output(vec1.size()+vec2.size()); auto last = std::set_intersection(vec1.begin(),vec1.end(), vec2.begin(),vec2.end(),output.begin()); std::cout << "\n Shared elements: "; for ( auto it = output.begin(); it != last; it++) std::cout << *it << " "; std::cout<<std::endl; return 0; }
An array is called a monotonic array if it is either monotone growing or monotone shrinking. In simple words, if your array is either in non-increasing order or nor-decreasing order then this type of array is called a monotonic array.
Example:
{1,2,2,3,4,5,6} -> This is a monotonic array (Non-decreasing) {1,4,6,3,4,3,6} -> This array is not a monotonic array {7,6,5,4,4,3,1} -> This is a monotonic array (Non-increasing)
Algorithmic Definition
An array A is monotone growing if for all i <= j, A[i] <= A[j]. An array A is a monotone shrinking if for all i <= j,A[i] >= A[j]..
Approach to find montonic array
You can solve this problem by using various techniques. The solution to the problem is not that complex as you are considering. It’s just a little bit tricky. Before addressing, the solution let’s initially examine the problem. By observing we can assume that if you find a non-decreasing or non-increasing component we reach our solution by stating it as a non-monotonic problem.
So How we find an un-matching element in the array. You can tackle this difficulty using two pointers while iterating the array. We use two pointers i and j where i is following j we compare values at ith and jth index and using that result we further analyze the next element in the array with our result if it meets the function requirement. we further iterate the array else we break the loop and return the contemporary status of the function to the user.
Algorithm for monotonic array
initiate j =1 ; status= 2 (non-monotonic)
iterate a for loop from zero to size of the array-1;
if j will become less then i or equal to the size of the array return the current status.
else if the value at i is greater than the value at j. Mark status = 0.
if the value at j+1 is greater than the value at j or status =1. Mark status=2 and return it. else increase j by 1.
else if the value at i is less than the value at j. Mark status = 1
if the value at j+1 is less than the value at j or status =0. Mark status=2 and return it. else increase j by 1
else increase j by 1.
do all 4,5,6 until 3 is not true.
return the status.
Implementation of the monotonic array in c++
/* Monotonic array : If an array is entriely non-decreasing or non-increasing order Problem description : you have given array find if it is monotonic or not.. */ #include<iostream> #include<vector> int isMonotoinc(std::vector<int>v) { int j=1; // 2=> null direction 0=> decreasing 1=> increasing int status=2; for(int i=0;i<v.size();i++) { if(j<=i || j>=v.size()){ break; } else if(v.at(i)>v.at(j)){ status=0; if(v.at(j+1)>v.at(j) || status ==1){ status=2; return status; } j++; } else if(v.at(i)<v.at(j)){ status=1; if(v.at(j+1)<v.at(j) || status ==0){ flag=2; return status; } j++; } else { j++; } } return status; } int main(){ std::vector<int>v1={1,2,2,3,4,5,6,6}; if(isMonotoinc(v1)==1) { std::cout << " IT is non decreasing"; } else if(isMonotoinc(v1)==0){ std::cout << " IT is non Increasing"; } else{ std::cout << " IT is not monolotic"; } }
In three number sum problem, you have given an array of integers, you have to find the total sets of integers by adding them we can get our target sum.
A simplistic approach is to produce all possible sets of numbers and compare the sum of each set to our target sum. If it satisfies our condition then we insert that set of integers in our product array and proceed further till we will not iterate all elements.
Algorithm
Given an array of length N and target sum T.
design three nested loop first loop runs from start to end (iterator i), the second loop runs from i+1 to end (iterator j) and the third loop runs from j+1 to end (iterator k).
The iterator of these loops denotes the index of 3 elements of the set of elements.
Find the sum of ith, jth, and kth element. If the sum is equal to the target sum. Insert the set of elements in our final array.
After completion return the output array.
Complexity Analysis
Time complexity analysis: There exist three nested loops traversing the array, so the time complexity will be O(n3) Space Complexity: No extra space is required O(1)
Implementation in C++
#include<iostream> #include<vector> using myvec=std::vector<int>; std::vector<myvec> three_Sum(myvec arr,int target) { myvec result; for (int i = 0; i < arr.size(); i++) { for (int j = i + 1; j < arr.size(); j++) { for (int k = j + 1; k <arr.size(); k++) { if (A[i] + A[j] + A[k] == target) { myvec temp={arr.at(i),arr.at(j),arr.at(k)}; result.push_back(temp); } } } }
} return 0; } // You can use this code for educational purpose only //( copyright coderca 2020)
Method 2
By Sorting the array the effectiveness of the algorithm can be increased. This effective procedure uses the two pointers to solve this particular problem. Traverse the array and set the first element of the set. Now set the first pointer to i+1 and the second pointer to n-1. to find if there is a pair whose sum is equal to targetSum – array[i]. If there is then add the set of (i, left, right ) to our output array.
Algorithm
Sort the given array.
iterate the array and fix the first element to the arr[i].
Then fix two pointers, left to i + 1 and the right to n – 1. And look at the sum of ( arr[i], arr[left], arr[right].
If the sum equals the target sum then insert the set into our output array.
increase left by 1 and decrease right by 1.
Else, If the sum is bigger than the target sum, Decrease the right by 1;
Else, if the sum is smaller than the target sum, increase the left by 1;
do 3,4,5,6 while the left is smaller than right.
return the output array.
Complexity Analysis
Time complexity analysis: It takes O(nlogn) time to sort and There exist two nested loops traversing the array, so the time complexity will be O(n2) Space Complexity: No extra space is required O(1)
Implementation in C++
// three number sum equals to a target problem // time-complexity =O(N^2) // space-complexity=O(N) #include<iostream> #include<thread> #include<vector> #include<algorithm> using myvec=std::vector<int>; std::vector<myvec> three_Sum(myvec arr,int target) { std::vector<myvec> result; std::sort(arr.begin(),arr.end()); for(int i=0;i<arr.size();i++){ int left=i+1; int right=arr.size()-1; while (left!=right && left<right) { if(arr.at(left)+arr.at(right)+arr.at(i)==target) { myvec temp={arr.at(i),arr.at(left),arr.at(right)}; result.push_back(temp); left=left+1; right=right-1; } else if(arr.at(left)+arr.at(right)+arr.at(i)<target) { left=left+1; } else if(arr.at(left)+arr.at(right)+arr.at(i)>target) { right=right-1; } }
we need an effective way to examine if the counterpart exists in the vector. If the counterpart exists, we will return the pair of elements. What is the most reliable way to keep a mapping of each element in the vector? A hash table.
We reduce the searching time from O(n2) to O(n) by trading space for speed. A hash table is created precisely for this goal, it maintains active lookup in Expected-constant time. I say “expected” because if a collision happened, a lookup could degenerate to O(n2) time. But look up in hash table should be amortized O(n) time as long as the hash function was selected precisely.
A simple implementation uses a unordered_map. while iterating we check if a counterpart has existed in the hash or not. if it presents we return the pair of the value else we insert the value at that index to the hashtable.
In this article, we are going to learn about vector. Before understanding vector. let’s first discuss arrays. You have used arrays a lot where you can store data in a sequential way. There is a lot of use of arrays since programming has been started. You are using arrays in the implementation of Queue stack and in many more virtual Data structures. You can say arrays are the lifeline of programmers.
So what is the problem with the array? No! There is no problem with standard arrays. It’s a limitation of arrays that is stopping you to do a lot with arrays. Let’s first discuss the features of standard arrays in brief.
Properties of arrays
Array stores data in sequential way.
Arrays Always created with the fixed size. You have to define the size of array while creation.
Time complexity of accessing elements is just O(1) because all data sequential way.
Memory allocation for the array is at compile time in stack.
int arr[10] ; here we have decided the size of array at compile time.
There is a lot of features of arrays but that is not relevant for this article. We will talk about them in another article. The main issue with the array is that it is a fixed-size data structure that once you created an array you can not increase the size of the array. You can not insert more elements in an array.
For solving this problem we created the linked list. Where we can store data dynamically but the main problem with the linked list is that cost of accessing the data is O(n). You have to iterate the linked list from start to your element to access the data.
The programmer of STL thinks that, can we create new data structures which can access data in O(1) and We can also store data dynamically without declaring the size of the array. This is the reason for vectors' existence in C++.
What is Vector
Vector is a special type of class in STL library which have the functionality of both arrays and linked list. It is a sequential container also known as dynamic arrays. It can store data in an array dynamically and access elements in O(1). There is no need to provide the size of the array at compile time because Its size can grow and shrink dynamically according to our needs. Let see a few points of vectors before understanding it.
Properties of Vector
Syntax for STL vector is : std::vector<T> vec .
Std::vector is a sequence container and also known as Dynamic Array or Array List.
Vector size can grow and shrink dynamically. There is no need to provide size at compile time.
Vectors have functions for accessing elements at(), [], front(), back(), data().
Functions for modifying vector insert(), emplace(), push_back(), emplace_back(), pop_back(), resize(), swap(), erase(), clear() etc.
std::vector vec;
Here we have created an object of class vector with name vec.
Various operations on Vector
std :: vector declaration
There are three ways to declare vector in C++. We are going to see all of them one by one in this section.
std :: vector<int> vec;
Here we have declared an integer type of vector without initializing with any data.
std :: vector <int> vec (5,20);
We have created a vector of size 5 and initialized all elements of vector with 20.
std :: vector <int> vec = {1,2,3,4,5,6};
Here we directly stored data in vector as we stored in array.
Accessing the elements from a std :: vector
There are two ways of accessing elements from the vectors in C++. We are going to see all of them one by one in this section.
vec[3];
It returns the value at index three from the vector. If you go out of bound it will give you garbage value. That means if you have let say 10 elements in your array then if try to access value from out of bound that it will return a garbage value.
vec.at(3) ;
It returns the value at index three from the vector. If you go out of bound it will give you an exception. That mean if you have let say 10 elements in your array than if try to access value from out of bound that it will give you exception.
vec.front() ;
It returns the first element of the vector.
vec.back() ;
It returns the last element of the vector.
std::vector Modifiers
In this section We are going to discuss all vectors modifiers that are available in C++ STL in details
vector :: push_back()
This function is used to add an element at end of the vector. It insert element at last in our array.
vec.push_back(12); It inserted 12 at last of our array.
vector :: pop_back()
This is used to delete last elements from the vector.
vec.pop_back(); It removes the last element from our array.
vector :: swap()
This function is used to swap all content of two vectors of same types. Type of both vectors must be same for swapping the content.
We use clear to delete all elements from the vector. It will make size of vector 0.
vec.clear();
It will delete all data of vector vec.
vector :: erase()
This function also deletes data from your container. This function comes with an extra edge, here you can specify the range in between you want to delete data from your vector. You can also delete it at a specific position.
1 vec.erase (position) ; It will delete data of a specific index from your vector.
2. vec.erase(start,end); It will delete all data within range of start to end index.
vector :: resize()
This function is used to change the size of your vector. If given size is greater then actual size of vector then it add extra space in your vector. If given size is less then the actual size of vector it deletes the elements from your vector.
1 vec.resize(n); It will make your vector’s size n;
2. vec.resize(n,val); If size of your vector is less then n than It fill remaining value with the val in your vector.
vector :: insert()
We use this function to insert a value/object a particular position in vector. We pass the position and the value as parameter in the function. It is an inefficient way of doing it, because all member of vector reallocate their position for the insertion.
Vec.insert(pos,value); It will insert value at particular index in your vector.
More Usefull std::vector functions
In this section We are going to discuss all various std :: vector function that can help us in writing more neat clean code.
vector :: data()
It return the pointer that is pointing to our vector/array. In other we can say it return the pointer to the first element of our vector.
int* p = vec.data(); Here p is pointing to the our vector's first element
vector :: capacity()
It returns the no of elements that can be inserted in our vector.
int c=vec.capacity();
vector :: size()
It returns no of elements that are currently present in our vector
int s= vec.size()
vector :: shrink_to_fit()
It removes blank spaces from our vector and decrease the capacity of the vector to the size of the vector.
vec.shrink_to_fit();
It will remove all unused of vector vec.
vector :: reserve()
This function requests our compiler to reserve no of spaces for our vector. Or you can say we requests compiler to fix the minimum capacity for our vector. So class have not to do array creation again and again.
vec.reserve(300);
It will reserve 300 spots for storing the data in our vector object.
C++ pseudo code for vectors implementation
#include <iostream> #include <vector> int main(){
//created vector std::vector<int> vec; // insertion from 0 to 99 in vector for(int i=0;i<99;++i){ vec.push_back(i); } // printed the vector for(int i=0;i<vec.size();++i){ std::cout<<vec.at(i)<<std::endl; } // deleted last element from the vector vec.pop_back(); //inserted 123 at index : 20 in vector vec.insert(vec.begin()+20,123); // stores size of the vector in sz; int sz=vec.size(); //stores capacity of vector in ca; int ca=vec.capacity(); // It deleted the data from index 12 to 23 // vec.begin points to the first element; vec.erase(vec.begin()+12,vec.begin()+23); // Now it deleted all data from the vector vec.clear(); std::cin.get();
Ever wondered about your code that It is taking a lot of time to execute. Your code’s time complexity is so much high, even you have optimized your code. Then a question came in your mind, how can I make my code more efficient fast, and reliable. The answer is yes. Here is the role of multi-threading came. Where you can run several functions at the same time in your code and your running time decrease hell a lot.
Thread:
You don’t have to think a lot to know about a thread. You can understand thread by a simple line. It is a group a bunch of instructions that are packed together to executed. When that thread will be initiated in your code.
void fun() { std::cout<<"fun is calling"<<std::cout<<endl; } int main() { std::thread t1(fun); t1.join();
Explanation
Here you can see we have declared and defined a function named asfun function pointer We have assign it to the thread t1.
You have a question in your mind we can do the same task without using the thread. Yes, you are right you can do all of it without creating a new thread. Because your code is running inside the main() thread. In this example, we have used only 1 thread. Now you wanna do multiple works simultaneously then what you will do? for understanding this concept let’s jump to the concept of Multi-threading before It becomes more confusing.
Multi-threading:
When you are running more than one thread at the same time then It is known as multi-threading. Let’s go deep down to understand the concept of threading.
Explanation
In the right flowchart we have used the traditional way of coding and inside our main() thread all function has been called one by one and executed. Let's make the time complexity of a single function is O(1) so in this traditional way of coding your overall time complexity will be if you have let say ‘ n ‘ of function, O(n).
Now let’s come to the left flowchart where we have used the concept of multi-threading and executed all threads at the same time so if the time complexity of running a single thread is O(1) so if you run ‘n’ simultaneously then time-complexity remain same O(1) because all threads are running in parallel.
Traditional Coding
#include <iostream> void fun1() { std::cout<<"fun1() is calling "<<std::endl; } void fun2() { std::cout<<"fun2() is calling "<<std::endl; } void fun3() { std::cout<<"fun3() is calling "<<std::endl; } int main() { fun1(); fun2(); fun3(); std::cin.get(); }
When you are dealing with a lot of data and performing operations on it. You need a mechanism where you can do multiple operations simultaneously on that data. At that time if you will not use multi-threading then your process will become slower. In the industry, slow means No.
So should you use multi-threading always? No. You should not! It depends on what type of application you are developing. Is every module of your code needed multiple processes at the same time? We also have to check the dependency of processes on each other. Because sometimes a single process is dependent on the result of another process. At that point, we have to take care of it.
We are going to talk about it in more detail in further articles on the multi-threading series. Where we are gonna discuss different scenarios where we need multi-threading and where not. We will discuss all the cool stuff of Multi-threading in upcoming articles.
An array is a set of items stored at adjacent memory locations. The idea is to store various items of the same data type collectively. This makes it easier to determine the location of each component by simply joining an offset to a base value, i.e., the memory location of the first component of the array (usually expressed by the name of the array). The base value is index 0 and the disparity between the two indexes is the offset. For clearness, we can think of an array a line of stairs where on each step is placed a value (let’s assume one of your mates). Here, you can identify the location of any of your friends by simply identifying the count of the step they are on. Mainly in this article, we are talking about static arrays.
Size of the array
In C++ language array has a fixed size recommending one’s size is given to it. It can’t change (Only for static array). The intention was that for expanding if we alter the size we can’t be certain that we get the next memory position to us as free. The shrinking will not act because the array when listed, becomes memory statically, and hence compiler is the only one to kill it.
Models of indexing in the array
0 (zero-based indexing): The first component of the array starts from index 0.
1 (one-based indexing): The first component of the array starts from index 1.
Advantages of array
Arrays allow arbitrary access of components. This makes accessing components by position quicker.
Arrays have better cache locality that can obtain a pretty big difference in execution.
Accessing elements in the array is O[1].
Using arrays, other data structures like linked lists, stacks, queues, trees, graphs can be implemented.
Accessing the element is faster then any of the data structures available.
Disadvantages of using array
Static arrays are implemented on the stack and they are fixed size so you can not increase or decrease the size of the array once it has been declared.
You have to provide the size of the array during compile time.
Example
//integer array int arr[]={15,16,20,24,5,19,18}; // accessing and printing component from the array cout<<arr[4];
// Char array char arr[]={'a','b','c','d'};
C++ code for example
#include<iostream> int main(){ // declayring the array; int arr[7]; //assigning values to array arr={15,16,20,24,5,19,18}; //changing the value of a component at perticular index arr[5]=23; //printing the values of the array for(int i=0;i<7;i++){ std::cout<<arr[i]<<" "; } }
Everyone knows about the linear search algorithm and it's working.Today I will tell you how can you improve your linear search algorithm with some improvement in your code. Let's first talk about linear search:
Linear search is a basic algorithm where we compare elements one by one with our key element.
here is an Array of 10 elements in which we have to search 33 ..
Loop will start from index 0 = 12 and we compasre it with key 33 and we do comparison till we will not get the key ..
Algorithm:
int key;
for(int I=0;i<length;i++)
if(A[I]==key)
return I;
so here if key will be found at nth index then the total comparison will be O(n)..
here is a catch to improve the time complexity of given problem by adding some extra bit of code.
It will make your linear search algorithm a smart algo..
Smart Linear search 1 :
In above problem we were searching 33 and we find it at index 7.so next time if again search for 33 how much time it will take , 7 right .. yups but using this algorithm you can reduce the search time by 1 unit ..
Algorithm :
int key;
for(int I=0;i<length;i++)
if(A[I]==key)
swap(A[I] ,A[I-1])
return I-1;
so if you use above algorithm in your code it will reduce the running time by 1 unit in each iteration.
It will help you searching those key elements which you searched repeatedly .
Let's analyze it.
We were searching 33 and it found at index 7 and then we swap the index 7 with index 6 so the 33 now at index 6 .. so if you again search 33 you will get it 1 unit before the ideal Linear search algorithm.
Smart Linear search 2 :
this algorithm reduces the complexity rapidly if you search key value repeatedly . here's the algorithm for doing it.
Algorithm :
int key;
for(int I=0;i<length;i++)
if(A[I]==key)
swap(A[I] ,A[0])
return 0;
Time Complexities :
Standard Linear Search (For repeatedly Search of same Key ) = O(n);
Advanced Linear Search 1 (For repeatedly Search of same Key ) = O(n-1);
Advanced Linear Search 2 (For repeatedly Search of same Key ) = O(1);