C++ Vector Tutorial With Example | Vector in C++ STL is today’s topic. C++ Vector is a template class that is a perfect replacement for the right old C-style arrays. It allows the same natural syntax that is used with plain arrays but offers a series of services that free the C++ programmer from taking care of […]

The post C++ Vector Tutorial With Example | Vector in C++ STL appeared first on AppDividend.

]]>C++ Vector Tutorial With Example | Vector in C++ STL is today’s topic. C++ *Vector* is a template class that is a perfect replacement for the right old C-style arrays. It allows the same natural syntax that is used with plain arrays but offers a series of services that free the **C++ programmer** from taking care of the allocated memory and help to operate consistently on the contained objects.

C++ Vector is a sequence of container that can be changed dynamically. Means you can change its size any time you want. Like an array, it also takes contiguous memory location, but the difference is Vector is dynamic where Array is not. So, let’s start the **C++ Vector Tutorial With Example** From Scratch.

The C++ STL (Standard Template Library) is a powerful set of C++ template classes to provide general-purpose classes and functions with templates that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks.

The first step using a **vector** is to include the appropriate header.

#include <vector>

Note that the header file name does not have any extension; this is true for all of the Standard Library header files. The second thing to know is that all of the Standard Library lives in the namespace *std*. This means that you have to resolve the names by prepending *std::* to them.

Before using a vector, you have to include the header file **vector. **See the below code.

#include<iostream> #include<vector> int main() { return 0; }

For small projects, you can bring the entire namespace *std* into scope by inserting a using directive on top of your **cpp** file.

See the following syntax.

vector<object_type>vector_name;

See the following example.

#include<iostream> #include<vector> int main() { vector<int> v; return 0; }

An assign() modifier is used to assign the content to the vector.

The** vector:: assign()** is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary.

vector.assign(int size, int value)

**size**: The number of values to be assigned value.**value**: To be assigned to the vector name.

It pushes the elements into a vector from the back. It adds an element at the end of the vector. The new value is inserted into the vector at the end after the current last element, and the vector container size is increased by 1.

vector.push_back(value)

The **value** parameter is required, and it is the value that needs to be added.

It will delete the last element from a c++ vector. The pop_back() function is used to pop or remove elements from a vector from the back. The value is removed from the vector from the end, and the container size is decreased by 1.

vector.pop_back()

It inserts new elements before the element at the specified position. It inserts the elements into the vector.

vector.insert (position, value)

**position**: It specifies the iterator which points to the position where the insertion is to be done.**value**: It specifies the value to be inserted.

It erases the element from the vector. The erase() function is used to remove the element from specified positions. Elements are removed from the specified position of the container.

vector.erase(startpos, endpos)

It has either **startpos** or **endpos** parameters or only **startpos** parameter.

It swaps the **content in vector. This function is used to swap the contents of one vector with another vector of the same type and size.**

vector1.swap(vector2)

Vector2 is the parameter with which the content has been swapped.

It clears the vector. The clear() function is used to remove or delete all the elements of the vector container, thus making it size 0.

vector.clear()

The **vector::emplace()** is the STL in C++ which extends container by inserting the new element at the position. Reallocation happens only if there is the need for more space. Here the container size increases by one. It constructs and inserts the element in the vector.

template <class... Args> iterator emplace (iterator_position, Args&&... args);

The function accepts two mandatory parameters which are specified as below.

- iterator_position – It specifies the iterator pointing to the position in the container where the new element is to be inserted.
- args – It specifies the element to be inserted in the vector container.

The emplace_back() function is used to insert a new element into the vector container; the new item is added to the end of the vector.

vector.emplace_back(value)

The value to be inserted into the vector is passed as the parameter.

See the following code example of C++ Vector Modifiers.

#include<bits/stdc++.h> #include<vector> using namespace std; int main() { vector<int>v1; //assign the vector with 5 times 50 v1.assign(5,50); cout<<"After assign the vector is: "; for(int i=0;i<v1.size();i++) { //v1.size() will return size of vector cout<<v1[i]<<" "; } cout<<"\n"; //====================================================================================// //insert 100 at the last of the vector //using push_back() v1.push_back(100); int n=v1.size(); cout<<"The last element of the vector right now is: "<<v1[n-1]<<" and size: "<<n<<"\n"; //====================================================================================// //delete the last element of the vector //using pop_back() v1.pop_back(); n=v1.size(); cout<<"After removing the size of vector is "<<n<<" & last element is "<<v1[n-1]<<"\n"; //====================================================================================// //insert 70 at the front of the vector //using insert() v1.insert(v1.begin(),70); cout<<"After inserting at begining the front value is: "<<v1[0]<<"\n"; //======================================================================================// //remove the first element using erase v1.erase(v1.begin()); cout<<"After inserting at begining the front value is: "<<v1[0]<<"\n"; //=====================================================================================// //swap first and last element of the vector //using swap() n=v1.size(); cout<<"Before swapping the fisrt value is "<<v1[0]<<" last value: "<<v1[n-1]<<"\n"; swap(v1[0],v1[n-1]); cout<<"After swapping the fisrt value is "<<v1[0]<<" last value: "<<v1[n-1]<<"\n"; //======================================================================================// //insert element at front using emplace() v1.emplace(v1.begin(),12); v1.emplace(v1.begin(),12); cout<<"After inserting at begining the front value is: "<<v1[0]<<"\n"; //=======================================================================================// //insert element at the back of the vector //using emplace_back() v1.emplace_back(60); n=v1.size(); cout<<"After inserting at back of the back value is: "<<v1[n-1]<<"\n"; //========================================================================================// //clear all the element of the vector v1.clear(); n=v1.size(); cout<<"After clearing the size of vector is: "<<n<<"\n"; //================================================================================================// return 0; }

The output is following.

**Here one thing to note that emplace() and emplace_back() works on c++11 or above. So if your version is lower, then it might not work.**

The Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. See some below vector iterators.

The begin() function is used to return an iterator pointing to the first element of the vector container.

vector.begin()

The end() function is used to return an iterator pointing to next to the last element of the vector container.

vector.end()

The function returns an iterator which is used to iterate container.

- The iterator points to the beginning of the vector.
- Iterator cannot modify the contents of the vector.

vector.cbegin()

The cend() function returns an iterator which is used to iterate container.

- The iterator points to the
element of the vector.*past-the-end* - Iterator cannot modify the contents of the vector.

vector.cend()

It returns the const_reverse_iterator pointing to the last element in the container. Means this will return the last element of the vector.

const_reverse_iterator crbegin() const noexcept;

It’s a public member function that returns a const_reverse_iterator pointing to the element preceding the first element.

const_reverse_iterator crend() const noexcept;

The** vector::rbegin()** is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container.

vector.rbegin()

The** vector::rend()** is a built-in function in C++ STL which returns a reverse iterator pointing to the theoretical element right before the first element in the array container.

vector.rend()

See the following iterators example in C++ Vector.

#include <iostream> #include <vector> using namespace std; int main() { //First insert some element to the vector vector<int> v1; int n,x; cout<<"Enter the size of the vector: "; cin>>n; cout<<"Enter vector values:\n"; for (int j=0;j<n;j++) { cin>>x; v1.push_back(x); } //================Print all element using begin() & end()==========================// cout<<"Output of all elements using begin() & end(): "; for (auto i =v1.begin(); i!=v1.end();++i) cout<<*i<<" "; //=====================Print all element using cbegin() & cend()======================// cout<<"\nOutput of all elements using cbegin and cend: "; for (auto i=v1.cbegin();i!=v1.cend(); ++i) cout<<*i<<" "; //====================Print all element using crbegin() & crend()===================// cout<<"\nOutput of all elements using crbegin and crend: "; for (auto i=v1.crbegin();i!=v1.crend();++i) cout<<*i<<" "; //=====================Print all element using rbegin() & rend()==========================// cout<<"\nOutput of all elements using rbegin and rend: "; for (auto i=v1.rbegin();i!=v1.rend();++i) cout<<*i<<" "; //========================================================================================// return 0; }

The output is following.

Vector capacity returns the size of allocated storage capacity. It returns the size of the storage space currently allocated for the vector, expressed in terms of elements.

The capacity is not necessarily equal to the vector size. It can be similar or higher, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion.

See some of the capacity functions in vector.

The **size()** function is used to return the size of the vector container or the number of elements in the vector container. It returns the size of the vector.

vector.size()

It returns the maximum size of the vector. The **vector::max_size()** is a built-in function in C++ STL which returns the maximum number of elements that can be held by the vector container.

vector.max_size()

It is used to change the size of the vector. The resize() function alters the container’s content in actual by inserting or deleting the elements from it.

vector.resize(int n, int value)

**n:**it is a new container size, expressed in the number of elements.**value**: if this parameter is specified then new elements are initialized with this value.

It returns the size of the allocated storage capacity. The **vector::capacity()** function is the built-in function which returns the size of the storage space currently allocated for a vector, expressed in terms of items.

vector.capacity()

The empty() function is used to check if the vector container is empty or not. It is used to test whether the vector is empty.

vector.empty()

The **reserve() function **helps the user specify the minimum size of the vector. It indicates that the vector is created such that it can store at least the number of the specified elements without having to reallocate memory.

vector.reserve(n)

Argument n which denotes the no of elements to be stored in a vector.

The **vector::shrink_to_fit()** function reduces the capacity of the container to fit its size and destroys all elements beyond the capacity.

vector.shrink_to_fit()

#include<iostream> #include<vector> using namespace std; int main() { //First insert some element to the vector vector<int> v1; int n,x; cout<<"Enter the size of the vector: "; cin>>n; cout<<"Enter vector values:\n"; for (int j=0;j<n;j++) { cin>>x; v1.push_back(x); } //=======================Demonstrate size()===============================// cout<<"Size of the vector is: "<<v1.size()<<"\n"; //======================Demonstrate max_size()=======================================// cout<<"\nMax_Size of the vector is: "<<v1.max_size(); //======================Demonstrate capacity()======================================// cout<<"\nCapacity of the vector is: "<<v1.capacity(); //======================Resize the vector to n-2===================================// v1.resize(n-2); cout<<"\nAfter resize the Size of the vector is: "<<v1.size(); //=====================Demonstrate reserve() =====================================// cout<<"\nBefore reserve the size of the vector is: "<<v1.size(); cout<<"\nBefore reserve the capacity of the vector is: "<<v1.capacity(); v1.reserve(40); cout<<"\nAfter reserve the capacity of the vector is: "<<v1.capacity(); cout<<"\nAfter reserve the size of the vector is: "<<v1.size(); //======================Shrink the vector==========================================// v1.shrink_to_fit(); cout << "\nVector elements are: "; for (auto i=v1.begin();i!=v1.end();i++) cout<<*i<<" "; //=====================Clear all elements and check if the vector is empty================// v1.clear(); if (v1.empty() == false) cout<<"\nVector is not empty"; else cout<<"\nVector is empty"; //============================================================================================// return 0; }

The output is following.

Here, we will discuss different techniques to get an element from the vector by index or position. We will see some of the methods that can use to access the element in the vector.

The operator is used to reference the element present at a position given inside the operator. It accesses the specified element at position i.

vectorname[position]

The position argument is the position of the element to be fetched.

The at() function is used reference the element present at the ** position** given as the parameter to the function.

vector.at(position)

It is the position of the element to be fetched. It provides a reference to an element.

The front() function can be used to fetch the first element of a vector container. Returns the reference to the first element of the vector.

vector.front()

The back() function can be used to fetch the last element of a vector container. Returns the reference to the last element of the vector.

vector.back()

It writes the data of the vector into the array. The **std::vector::data()** is an STL in C++ which returns a direct pointer to the memory array used internally by the vector to store its owned elements.

vector.data()

Now, see the below C++ program.

#include<iostream> #include<vector> using namespace std; int main() { //==================First insert some element to the vector==========================// vector<int>v1; int n,x; cout<<"Enter the size of the vector: "; cin>>n; cout<<"Enter vector values:\n"; for (int j=0;j<n;j++) { cin>>x; v1.push_back(x); } //================== Show value at position 2 using Reference Operator ==============// cout<<"\nReference operator v1[2]= "<<v1[2]; //================== Show value at position 3 using at() =======================// cout<<"\nValue at position 3 is: "<<v1.at(3); //===================Show the first element of the vector========================// cout <<"\nFirst element of the vector is: "<<v1.front(); //================Show the last element of the vector===========================// cout << "\nLast element of the vector is: "<<v1.back(); //================Showing all the elements using data==========================// int* i=v1.data(); cout<<"\nAll the elements of the vector is:\n"; for(int j=0;j<v1.size();j++) { cout<<*i++<<" "; } return 0; }

The output of the above C++ program is following.

Conclusively, C++ Vector Tutorial With Example | Vector in C++ STL post is over.

The post C++ Vector Tutorial With Example | Vector in C++ STL appeared first on AppDividend.

]]>Quick Sort in C++ Tutorial With Example | C++ Quick Sort Program is today’s topic. Like Merge Sort, Quick Sort is also a recursive sorting algorithm which uses Divide and Conquer method. If you don’t know what Divide and Conquer are, then please read our Merge Sort tutorial first. British computer scientist Tony Hoare developed […]

The post Quick Sort in C++ Tutorial With Example | C++ Quick Sort Program appeared first on AppDividend.

]]>Quick Sort in C++ Tutorial With Example | C++ Quick Sort Program is today’s topic. Like Merge Sort, Quick Sort is also a recursive sorting algorithm which uses Divide and Conquer method. If you don’t know what Divide and Conquer are, then please read our Merge Sort tutorial first. British computer scientist Tony Hoare developed the QuickSort algorithm in 1959 and published in 1961. Quicksort is that algorithm which is being used most of the compiler in their **sort().**

In Quick Sort first, we need to choose a value, called **pivot** (preferably the last element of the array). Then, we arrange the smaller values towards the left side of the pivot and higher values towards the right side of the pivot. These two operations are performed recursively until there is only one element left at both the side of the pivot. Another word, quicksort algorithm is following.

QuickSort is a sorting algorithm, which is commonly used in computer science. QuickSort is a divide and conquers algorithm. It creates two empty arrays to hold elements less than the pivot value and elements more significant than the pivot value, and then recursively sort the sub arrays. There are two basic operations in the algorithm, swapping items in place and partitioning the section of an array.

Now, see the following example.

Suppose we are given an array.

15 | 85 | 32 | 4 | 21 | 24 |

So here our **pivot =24. **Now after arranging all smaller elements to the left side of 24 and more significant elements to the right side of 24, the array will be the following.

So after the first pass, 24 is placed its correct position. Now, we will again perform the partition operation to the left sub-array and the right sub-array and so on.

So, the operations will be at each step like the following.

What happened here is:

First, it called Quicksort(Array,start_index,end_index), then the partition() was called, and it arranged the smaller number at the left side of the pivot and higher numbers at the right side of the pivot. And again Quicksort() was called recursively. Like this way, we got 15 at last.

After that, the Quicksort() returned the sorted subarray at each step and then again the operations on right subarray was performed like the below image.

So, here I have shown you in these three pictures how Quicksort is performed recursively.

- Find a “pivot” element in an array. The pivot item is the basis for comparison for a single round.
- Start the pointer (the left pointer) at the first item in the array.
- Start the pointer (the right pointer) at the last item in the array.
- While the value at the left pointer in the array is less than the pivot value, move the left pointer to the right (add 1). Continue until the value at the left pointer is greater than or equal to the pivot value.
- While the value at the right pointer in the array is greater than the pivot value, move the right pointer to the left (subtract 1). Continue until the value at the right pointer is less than or equal to the pivot value.
- If the left pointer is less than or equal to the right pointer, then swap the values at these locations in an array.
- Move the left pointer to the right by one and the right pointer to the left by one.
- If the left pointer and right pointer don’t meet, go to step 1.

**QUICKSORT(A, start, end)**

- if start < end
- P_indx =PARTITION(A, start, end)
- QUICKSORT(A, start, P_indx-1)
- QUICKSORT(A, P_indx +1, end)
- Exit

**PARTITION(A, start, end)**

- Set pivot = A[end]
- Set P_indx = start
- Repeat step 4 to 7 for j = start to end – 1
- if A[j]<=pivot
- exchange A[P_index] with A[j]
- Set P_index=P_index+1

[End of If block]

- exchange A[P_index] with A[end]

[End of For Loop]

8. return P_index

See the below C++ Quicksort code.

#include<bits/stdc++.h> using namespace std; int partition(int *a,int start,int end) { int pivot=a[end]; //P-index indicates the pivot value index int P_index=start; int i,t; //t is temporary variable //Here we will check if array value is //less than pivot //then we will place it at left side //by swapping for(i=start;i<end;i++) { if(a[i]<=pivot) { t=a[i]; a[i]=a[P_index]; a[P_index]=t; P_index++; } } //Now exchanging value of //pivot and P-index t=a[end]; a[end]=a[P_index]; a[P_index]=t; //at last returning the pivot value index return P_index; } void Quicksort(int *a,int start,int end) { if(start<end) { int P_index=partition(a,start,end); Quicksort(a,start,P_index-1); Quicksort(a,P_index+1,end); } } int main() { int n; cout<<"Enter number of elements: "; cin>>n; int a[n]; cout<<"Enter the array elements:\n"; for(int i=0;i<n;i++) { cin>>a[i]; } Quicksort(a,0,n-1); cout<<"After Quick Sort the array is:\n"; for(int i=0;i<n;i++) { cout<<a[i]<<" "; } return 0; }

The output is below.

The worst case occurs when the partition process always picks the greatest or smallest item as a pivot and the complexity of **Worst Case: O(N^2).**

The best case occurs when a partition process always picks the middle element as pivot. And the complexity of **Best Case: O(N).**

The average case means when there is neither a balanced tree nor like the Worst Case. The complexity of the **Average Case: (N log N).**

Actually, Time Complexity for QuickSort is O(n2). Its *average case* running time is O(nlog(n)), but its *worst-case* is O(n2), which occurs when you run it on the list that contains few unique items. Randomization takes O(n). Of course, it doesn’t change its worst case, it just prevents the malicious user from making your sort take a long time.

QuickSort is more popular because it:

- Is in-place (Merge Sort requires extra memory linear to a number of elements to be sorted).

- Has a small hidden constant.

Conclusively, Quick Sort in C++ Tutorial With Example | C++ Quick Sort Program is over.

The post Quick Sort in C++ Tutorial With Example | C++ Quick Sort Program appeared first on AppDividend.

]]>Merge Sort In C++ Tutorial With Example | C++ Merge Sort Program is today’s topic. Merge sort is an efficient and comparison based algorithm to sort an array or a list of integer you can say. It is a Divide and Conquer algorithm which was invented by John von Neumann in 1945. Now you may […]

The post Merge Sort In C++ Tutorial With Example | C++ Merge Sort Program appeared first on AppDividend.

]]>Merge Sort In C++ Tutorial With Example | C++ Merge Sort Program is today’s topic. Merge sort is an efficient and comparison based algorithm to sort an array or a list of integer you can say. It is a** Divide and Conquer** algorithm which was invented by John von Neumann in 1945. Now you may question what is Divide and Conquer method.

**Merge sort** first divides an array into equal halves and then combines them in a sorted manner.

You can check out Bubble Sort and Selection Sort examples in this blog.

Let’s discuss the divide and concur method. It has the following three tasks.

**Divide**the problems into subproblems that are similar to the original but smaller in size.**Conquer**the sub-problems in recursively. If they are smaller in size solve them in a straight forward manner.**Combine**those solutions to a solution which is the answer to the original problem.

Merge sort keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is only one element in the list, it is sorted. Then, merge sort combines the smaller sorted lists keeping the new list sorted too.

**Sorting Problem:** Sort a sequence of *n* elements into non-decreasing order.

*Divide***:** Divide the *n*-element sequence to be sorted into two subsequences of *n/2* elements each

** Conquer:** Sort the two subsequences recursively using merge sort.

*Combine***:** Merge the two sorted subsequences to produce the sorted answer.

The top-down merge sort approach a methodology which uses the recursion mechanism. It starts from the Top and proceeds downwards, with each recursive turn asking the same question such as “What is required to be done to sort the array?” and having an answer as, “split an array into two, make a recursive call, and merge the results.”, until one gets to the bottom of an array tree.

Okay, now before going to the code and all first understand a model of Merge Sort, this will help you to understand the code.

Let us consider a list of integer:

43 | 63 | 93 | 24 | 15 | 27 | 21 |

So, as per the algorithm, we first need to divide the length of the list (n) into two parts and so on until they are divided into one node only.

So here **n=7** now **n/2=3**. Thus, the first part will of 3 integers and the second part will be of **7-3=4** part.

**Note that: If the size of the list is even then both side will be divided equally. But for the case of ODD smaller size will be at the left side and more significant will be on the right side.**

So, after **Step1** the list will be divided like the following.

43 | 63 | 93 | 24 | 15 | 27 | 21 |

Like this again we will divide each of the lists by 2. So, Left side list will be in 1+2 and right side list will appear in the 2+2 part. The same thing will happen again until they all get separated. So, here we will see the Final list after the divide method. See the following figure.

Okay, after all the Divide operation performed, we will now perform **Conquer **that is Sort the two subsequences recursively using merge sort and** Combine **that is Merge the two sorted subsequences to produce the sorted answer operation.

So here we will see what will be the result after each step:

So, what happened here is… First it compared two sub-sequence, for example here 63 and 93 are checked and then they were placed in ascending order after the merge, similarly, 27 and 21 are checked and then placed ascending order after merged. Again in step two 43,63,93 were checked and placed in ascending order after merge. By this way, we got our **final shorted list.**

15 |
21 |
24 |
27 |
43 |
63 |
93 |

Merge Sort Pseudo Code is following.

procedure mergesort( var a as array ) if ( n == 1 ) return a var l1 as array = a[0] ... a[n/2] var l2 as array = a[n/2+1] ... a[n] l1 = mergesort( l1 ) l2 = mergesort( l2 ) return merge( l1, l2 ) end procedure procedure merge( var a as array, var b as array ) var c as array while ( a and b have elements ) if ( a[0] > b[0] ) add b[0] to the end of c remove b[0] from b else add a[0] to the end of c remove a[0] from a end if end while while ( a has elements ) add a[0] to the end of c remove a[0] from a end while while ( b has elements ) add b[0] to the end of c remove b[0] from b end while return c end procedure

See the following **mergesort.cpp** file.

#include<bits/stdc++.h> using namespace std; int Merge(int A[],int p, int q,int r) { int n1,n2,i,j,k; //size of left array=n1 //size of right array=n2 n1=q-p+1; n2=r-q; int L[n1],R[n2]; //initializing the value of Left part to L[] for(i=0;i<n1;i++) { L[i]=A[p+i]; } //initializing the value of Right Part to R[] for(j=0;j<n2;j++) { R[j]=A[q+j+1]; } i=0,j=0; //Comparing and merging them //into new array in sorted order for(k=p;i<n1&&j<n2;k++) { if(L[i]<R[j]) { A[k]=L[i++]; } else { A[k]=R[j++]; } } //If Left Array L[] has more elements than Right Array R[] //then it will put all the // reamining elements of L[] into A[] while(i<n1) { A[k++]=L[i++]; } //If Right Array R[] has more elements than Left Array L[] //then it will put all the // reamining elements of L[] into A[] while(j<n2) { A[k++]=R[j++]; } } //This is Divide Part //This part will Divide the array into //Sub array and then will Merge them //by calling Merge() int MergeSort(int A[],int p,int r) { int q; if(p<r) { q=(p+r)/2; MergeSort(A,p,q); MergeSort(A,q+1,r); Merge(A,p,q,r); } } int main() { int n; cout<<"Enter size of the Array: "; cin>>n; int A[n],i; cout<<"Enter array values:\n"; for(i=0;i<n;i++) cin>>A[i]; //Calling the MergeSort() //First we are passing the array //the start index that is 0 //and the size of the array n MergeSort(A,0,n-1); cout<<"The Sorted List is\n"; for(i=0;i<n;i++) { cout<<A[i]<<" "; } return 0; }

The output is following.

Running time *T***(***n***)** of Merge Sort:

- Divide: computing the middle takes Θ(1)
- Conquer: solving 2 sub-problems takes 2
*T*(*n*/2) - Combine: merging
*n*elements takes Θ(*n*) - Total time complexity is following.

T(n) = Θ(1) if n = 1T(n) = 2T(n/2) + Θ(n) if n > 1 T(n)= 2 T(n/2) + n = 2 ((n/2)log(n/2) + (n/2)) + n = n (log(n/2)) + 2n = n log n – n + 2n = n log n + n = O(n log n )

The above recurrence can be solved either using Recurrence Tree method or Master method. It falls in case II of Master Method and solution of the repetition is. O(n log n)

The time complexity of the Merge Sort is O(n log n) in all 3 cases (worst, average and best) as merge sort always divides the array into two halves and take linear time to merge two halves.

With worst-case time complexity being Ο(n log n), it is one of the most respected algorithms.

- Merge Sort is useful for sorting linked lists in O(nLogn) time.
- It is used in Inversion Count Problem.
- We can use in External Sorting.

Conclusively, Merge Sort In C++ Tutorial With Example article is over.

The post Merge Sort In C++ Tutorial With Example | C++ Merge Sort Program appeared first on AppDividend.

]]>Selection Sort In C++ Tutorial With Example | C++ Selection Sort Program is today’s topic. Like Bubble Sort, Selection Sort is also a sorting algorithm; especially it is an in-place comparison sort. Selection sort algorithm is based on an idea of finding the min or max element or item in the unsorted array and then […]

The post Selection Sort In C++ Tutorial With Example | C++ Selection Sort Program appeared first on AppDividend.

]]>Selection Sort In C++ Tutorial With Example | C++ Selection Sort Program is today’s topic. Like Bubble Sort, Selection Sort is also a sorting algorithm; especially it is an in-place comparison sort. Selection sort algorithm is based on an idea of finding the min or max element or item in the unsorted array and then putting it in its correct position in the sorted array.

Selection sort algorithm divides an array into **two parts**:

- A sorted subarray
- The unsorted sub-array, from where we have to pick the smallest element and then put it into the sorted array.

Selection sort is a very simple sorting algorithm. A selection sorting algorithm is an in-place comparison-based algorithm in which the list or an array is divided into two parts, the sorted part at the leftmost end and the unsorted part at the right most end. So, initially, the sorted part is empty, and the unsorted part is an entire list.

The smallest element is selected from an unsorted array and swapped with the leftmost element, and that element becomes the part of a sorted array. This process continues moving unsorted array boundary by the component to the right. Finally, we get the sorted values.

We will first see the algorithm, and then we will see an example of Selection Sort.

**Selection(A,N)**

**Step1: **Repeat step 2 and 3 for (k=0;k<n-1;k++)

**Step2: **Call MINIMUM(A,K,N,LOC)

**Step3: **Swap A[K] and A[LOC]

**Step4: **Exit

**Step1: **Set min=A[K] and LOC=K

**Step2: **Repeat step 3 and 4 for(i=k;i<n;i++)

**Step3: **if min>a[i]

**Step4: **set min=a[i] and LOC=i

**Step5: **Return LOC

So, from the algorithm what we can understand that, as said above the array is in two parts, one part is in sorted order, and another part is in unsorted order and from that unsorted order, we are finding the smallest value and putting it into sorted order list.

For example, Let’s take a list of integer:

Array Number | 12 | 10 | 86 | 4 | 13 |

Location | 0 | 1 | 2 | 3 | 4 |

When K=0; **SELECTION()** will call **MINIMUM() **and will check the smallest value from the list. So, here in the first pass, the lowest value will be 4, and the **MINIMUM()** will return the location of 4 that is **LOC=3**.

Then, **SELECTION()** will swap the value with current A[0]=12. So, after swapping the value new array will be:

Array Number | 4 | 10 | 86 | 12 | 13 |

Location | 0 | 1 | 2 | 3 | 4 |

Now, K=1 and again** SELECTION()** will call **MINIMUM()** and the then it will check the smallest value from the unsorted array, that is 10 and then it will return the location of 10, i.e., LOC=1.

As 10 is at its correct position so the final array will be the same as it is.

Now, K=2 and again** SELECTION()** will call **MINIMUM()** and the then it will check the smallest value from the unsorted array, that is 12, and then it will return the location of 12, i.e.,** LOC=3.**

Then, **SELECTION()** will swap the value with current A[2]=86. So, after swapping the value new array will be:

Array Number | 4 | 10 | 12 | 86 | 13 |

Location | 0 | 1 | 2 | 3 | 4 |

Now, K=3 and again** SELECTION()** will call **MINIMUM()** and the then it will check the smallest value from the unsorted array, that is 13, and then it will return the location of 13, i.e.,** LOC=4**.

Then, **SELECTION()** will swap the value with current A[3]=86. So, after swapping the value new array will be:

Array Number | 4 | 10 | 12 | 13 | 86 |

Location | 0 | 1 | 2 | 3 | 4 |

procedure selection sort list : array of items n : size of list for i = 1 to n - 1 /* set current element as minimum*/ min = i /* check the element to be minimum */ for j = i+1 to n if list[j] < list[min] then min = j; end if end for /* swap the minimum element with the current element*/ if indexMin != i then swap list[min] and list[i] end if end for end procedure

See the below code of the **selection.cpp.**

#include<bits/stdc++.h> using namespace std; int minimum(int a[],int n, int k, int loc) { loc=k; int min=a[k]; for(int i=k;i<n;i++) { if(a[i]<min) { min=a[i]; loc=i; } } return loc; } int selection(int a[],int n) { int loc=-1,k; for(k=0;k<n-1;k++) { int loc1=minimum(a,n,k,loc); int temp=a[k]; a[k]=a[loc1]; a[loc1]=temp; } cout<<"The sorted list is:\n"; for(k=0;k<n;k++) cout<<a[k]<<" "; } int main() { int n; cout<<"Enter the size of the array: "; cin>>n; int a[n],i; cout<<"Enter the array values:\n"; for(i=0;i<n;i++) { cin>>a[i]; } //calling selection function selection(a,n); return 0; }

If we want to find the minimum element from the array of N elements, N−1 comparisons are required. After putting the minimum item in its proper position, the size of an unsorted array reduces to N−1, and then N−2 comparisons are necessary to find the minimum in the unsorted array.

Therefore (N−1) + (N−2) + ……. + 1 = (N⋅(N−1))/2 comparisons and N swaps result in the overall complexity of O(N2).

So, the time complexity for selection sort is **O(n ^{2})** as there are two nested loops.

The good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation.

Conclusively, Selection Sort In C++ Tutorial With Example | C++ Selection Sort Program is over.

The post Selection Sort In C++ Tutorial With Example | C++ Selection Sort Program appeared first on AppDividend.

]]>Bubble Sort In C++ Tutorial With Example | C++ Bubble Sort Program is today’s topic. Bubble Sort is a sorting technique to sort an array, or we can say to sort a list of many numbers. This sorting algorithm is also known as Sinking Sort. Although this is the simplest method to sort the list […]

The post Bubble Sort In C++ Tutorial With Example | C++ Bubble Sort Program appeared first on AppDividend.

]]>Bubble Sort In C++ Tutorial With Example | C++ Bubble Sort Program is today’s topic. Bubble Sort is a sorting technique to sort an array, or we can say to sort a list of many numbers. This sorting algorithm is also known as **Sinking Sort. **Although this is the simplest method to sort the list of numbers, it is not the best way. We will discuss later it.

In this sorting method, each element is being compared with other elements of the list, and each time the largest, then the second largest, then 3rd largest number is placed at its correct position and so on until all the numbers are sorted. We will see one example of how it works?

Suppose we are given a list of number: **15 5 23 2 17. **Now, we will apply bubble sort in this example and will see how it works:

If we consider these numbers in an array, the array will be:

0 | 1 | 2 | 3 | 4 | Location |

15 | 5 | 23 | 2 | 17 | Array Value |

So, when we will apply bubble sort here, we will see how the array will change in each step.

[**15**, **5** ,23 ,2 ,17] ———-> [**5**, **15**, 23, 2 ,17]

[5, **15**,** 23**, 2, 17] ———-> [5, 15, 23, 2, 17]

[5, 15, **23**, **2**, 17] ———-> [5, 15, **2**, **23**, 17]

[5, 15, 2, **23**, **17**] ———-> [5, 15, 2, **17**, **23**]

So, as said above, after every pass, the largest number will be placed at its correct place. Here, if you notice, you can see that a number is being compared with its adjacent number, if that number is larger than the next number (adjacent number), then they are being swapped. Like, here we 1st compared between 15 and 5, as 15 is more significant than 5 so we have swapped them. Similarly, at the last step, 17 and 23 are compared, and then we have swapped them. So, the array finally became.

Location | 0 | 1 | 2 | 3 | 4 |

Array Value | 5 | 15 | 2 | 17 | 23 |

Okay, now we will see the next passes:

[**5**, **15**, 2, 17, 23] —————-> [**5**, **15**, 2, 17, 23]

[5, 15, 2, 17, 23] —————-> [5, **2**, **15**, 17, 23]

[5, 2, **15**, **17**, 23] —————-> [5, 2, **15**, **17**, 23]

[5, 2, 15, **17**,** 23**] —————-> [5, 2, 15, **17**, **23**]

So, after the second pass, we can see that only 2 is swapped with 15. Rest all are at its the correct position, although the pass was continued until it reached to the last number.

Now, after Second Pass the array is:

Location | 0 | 1 | 2 | 3 | 4 |

Array Value | 5 | 2 | 15 | 17 | 23 |

[**5**,** 2**, 15, 17, 23] ——————> [**2**, **5**, 15, 17, 23]

[2, **5**, **15**, 17, 23] ——————> [2, **5**, **15**, 17, 23]

[2, 5, **15**, **17**, 23] ——————-> [2, 5, **15**, **17**, 23]

[2, 5, 15, **17**, **23**] ——————-> [2, 5, 15, **17**, **23**]

Now, you might be thinking that why I continued the steps after getting the sorted list? The answer is, we have two nested loops, so we have to continue the loop until the loop reaches to its end point, no matter whether you got your sorted list or not.

Similarly, the **Fourth Pass** will also be executed without any reason:). But I am not going to show you that, as it’s going to be boring.

Instead, we will see its algorithm.

**Step1: **Take the input of **N** numbers as an array **arr**

**Step2: **Repeat step 2 to 5 For(i=0;i<n;i++)

**Step3: **For(j=0;j<n-i-1;j++)

**Step4: **if(arr[j]>arr[j+1]

**Step5: **swap(arr[j],arr[j+1])

**Step6: **End

In general, as we have N numbers, so we have to do

(N-1)+(N-2)+(N-3)+…+2+1 = **((N-1)*N)/2** comparisons.

So, the** complexity of the algorithm is O(n^2)**

This is for the worst case and average case

The complexity for **Best Case is O(n)**

#include<bits/stdc++.h> using namespace std; int main() { int n; cout<<"Enter number of element you want to store: "; cin>>n; int arr[n],i,j; cout<<"Enter array values:\n"; //taking the array value //from user for(i=0;i<n;i++) { cin>>arr[i]; } //Now we will sort the array for(i=0;i<n-1;i++) { for(j=0;j<n-i-1;j++) { //checking if previous value is //grater than next one or not if(arr[j]>arr[j+1]) { //temp will temporarly store //the value of arr[j] //then we will swap the values int temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } cout<<"After Bubble sort the array is:\n"; for(i=0;i<n;i++) cout<<arr[i]<<" "; return 0; }

The output is above the program is following.

Okay, now you might be thinking that cannot we **optimize this program** so that loop gets over when we encounter a sorted list?

My answer is **YES; **we can. For this, please refer to the given program:

Below is the optimized program.

#include<bits/stdc++.h> using namespace std; int main() { int n; cout<<"Enter number of element you want to store: "; cin>>n; int arr[n],i,j; cout<<"Enter array values:\n"; //taking the array value //from user for(i=0;i<n;i++) { cin>>arr[i]; } //here this flag will help //to optimise the solution //first initialise flag=1 int flag=1; //Now we will sort the array //if my flag value is 1 then only //the loop will execute for(i=0;i<n-1 && flag==1;i++) { //here after each time of j loop // we will re-initialize the flag to 0 flag=0; for(j=0;j<n-i-1;j++) { //checking if previous value is //grater than next one or not if(arr[j]>arr[j+1]) { //temp will temporarly store //the value of arr[j] //then we will swap the values int temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; //Here if there is a swap then // we will make it 1 flag=1; } } } cout<<"After Bubble sort the array is:\n"; for(i=0;i<n;i++) cout<<arr[i]<<" "; return 0; }

The output of the above program is following.

Finally, Bubble Sort In C++ Tutorial With Example | C++ Bubble Sort Program is over.

The post Bubble Sort In C++ Tutorial With Example | C++ Bubble Sort Program appeared first on AppDividend.

]]>