Write a program in c to implement a class to represent complex members . Include member function add and multiply two complex no .Overloaded assignment operator=

Classified in Computers

Written at on English with a size of 87.8 KB.

C++

LET

LET'S LEARN ABOUT BASIC C++

C++ Data Types - GeeksforGeeks

SOURCE : GEEKS FOR GEEKS

LET'S LEARN ABOUT LOOPS

FOR LOOP

#include <iostream>

usingnamespace std;

intmain(){for(int i =1; i <=5; i++)

{ cout <<" Good morning \n";}

return0;}

Loops in C++ 1

WHILE LOOP

#include <iostream>

usingnamespace std;

intmain()

{int i =0;// initialization expressionwhile(i <5)

// test expression

{ cout <<"Good morning\n"; i++;// update expression}

return0;}

Loops in C++ 1

 DO WHILE

#include <iostream>

usingnamespace std;

intmain(){int i =2;// initialization expressiondo{ cout <<" Good morning\n"; i++;// update expression}

while(i <1);//

test expression

return0;}

Output 2

SOME IMPORTANT C++ INTERVIEW QUESTIONS 

1. What are the different data types present in C++?

The 4 data types in C++ are given below:

  • Primitive Datatype(basic datatype). Example- char, short, int, float, long, double, bool, etc.
  • Derived datatype. Example- array, pointer, etc.
  • Enumeration. Example- enum
  • User-defined data types. Example- structure, class, etc.

2. What is the difference between C and C++?

C C++ C is a procedure-oriented programming language. C++ is an object-oriented programming language. C does not support data hiding. Data is hidden by encapsulation to ensure that data structures and operators are used as intended. C is a subset of C++ C++ is a superset of C. Function and operator overloading are not supported in C Function and operator overloading is supported in C++ Namespace features are not present in C Namespace is used by C++, which avoids name collisions. Functions can not be defined inside structures. Functions can be defined inside structures. calloc() and malloc() functions are used for memory allocation and free() function is used for memory deallocation. new operator is used for memory allocation and deletes operator is used for memory deallocation.

3. What are class and object in C++?

A class is a user-defined data type that has data members and member functions. Data members are the data variables and member functions are the functions that are used to perform operations on these variables.

An object is an instance of a class. Since a class is a user-defined data type so an object can also be called a variable of that data type.

A class is defined as-

class A{
private:
 int data;
public:
 void fun(){

 }
};

4. What is the difference between struct and class?

In C++ a structure is the same as a class except for a few differences like security. The difference between struct and class are given below:

Structure Class Members of the structure are public by default. Members of the class are private by default. When deriving a struct from a class/struct, default access specifiers for base class/struct are public. When deriving a class, default access specifiers are private.

5. What is operator overloading?

Operator Overloading is a very essential element to perform the operations on user-defined data types. By operator overloading we can modify the default meaning to the operators like +, -, *, /, <=, etc. 

For example -

The following code is for adding two complex number using operator overloading-

class complex{
private:
 float r, i;
public:
 complex(float r, float i){
  this->r=r;
  this->i=i;
 }
 complex(){}
 void displaydata(){
  cout<<”real part = “<<r<<endl;
  cout<<”imaginary part = “<<i<<endl;
 }
 complex operator+(complex c){
  return complex(r+c.R, i+c.I);
 }
};
int main(){
complex a(2,3);
complex b(3,4);
complex c=a+b;
C.Displaydata();
return 0;
}

6. What is polymorphism in C++?

Polymorphism in simple means having many forms. Its behavior is different in different situations. And this occurs when we have multiple classes that are related to each other by inheritance.

For example, think of a base class called a car that has a method called car brand(). Derived classes of cars could be Mercedes, BMW, Audi - And they also have their own implementation of a cars

The two types of polymorphism in c++ are:

  • Compile Time Polymorphism
  • Runtime Polymorphism

Polymorphism_in_C__.Png?1614777415

7. Explain constructor in C++

The constructor is a member function that is executed automatically whenever an object is created. Constructors have the same name as the class of which they are members so that compiler knows that the member function is a constructor. And no return type is used for constructors.

Example:

class A{
 private:
  int val;
 public:
  A(int x){             //one argument constructor
   Val=x;
  }
  A(){                    //zero argument constructor
  }
}
int main(){
 A a(3);     

 return 0;
}

8. Tell me about virtual function

Virtual function is a member function in the base class that you redefine in a derived class. A virtual function is declared using the virtual keyword. When the function is made virtual, C++ determines which function is to be invoked at the runtime based on the type of the object pointed by the base class pointer.

9. Compare compile time polymorphism and Runtime polymorphism

The main difference between compile-time and runtime polymorphism is provided below:

Compile-time polymorphism Run time polymorphism In this method, we would come to know at compile time which method will be called. And the call is resolved by the compiler. In this method, we come to know at run time which method will be called. The call is not resolved by the compiler.It provides fast execution because it is known at the compile time. It provides slow execution compared to compile-time polymorphism because it is known at the run time.It is achieved by function overloading and operator overloading. It can be achieved by virtual functions and pointers.

Example -

int add(int a, int b){
      return a+b;
}
int add(int a, int b, int c){
      return a+b+c;
}

int main(){
    Cout<<add(2,3)<<endl;
    Cout<<add(2,3,4)<<endl;


     return 0;
}

Example -

class A{
     public:
          virtual void fun(){
               Cout<<"base ";
          }
};
class B: public A{
     public:
          void fun(){
               Cout<<"derived ";
          }
};
int main(){
     A *a=new B;
     A->fun();

     return 0;
}

10. What do you know about friend class and friend function?

A friend class can access private, protected, and public members of other classes in which it is declared as friends.

Like friend class, friend function can also access private, protected, and public members. But, Friend functions are not member functions.

For example -

class A{
 private:
  int data_a;
 public:
  A(int x){
   Data_a=x;
  }
  friend int fun(A, B);
}
class B{
 private:
  int data_b;
 public:
  A(int x){
   Data_b=x;
  }
  friend int fun(A, B);
}
int fun(A a, B b){
 return a.Data_a+b.Data_b;
}
int main(){
 A a(10);
 B b(20);
 cout<<fun(a,b)<<endl;
 return 0;
}

Here we can access the private data of class A and class B.

11. What are the C++ access specifiers?

In C++ there are the following access specifiers:

Public: All data members and member functions are accessible outside the class.

Protected: All data members and member functions are accessible inside the class and to the derived class.

Private: All data members and member functions are not accessible outside the class.

12. Define inline function

If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time. One of the important advantages of using an inline function is that it eliminates the function calling overhead of a traditional function.

13. What is a reference in C++?

A reference is like a pointer. It is another name of an already existing variable. Once a reference name is initialized with a variable, that variable can be accessed by the variable name or reference name both.

For example-

int x=10;
int &ref=x;           //reference variable

If we change the value of ref it will be reflected in x. Once a reference variable is initialized it cannot refer to any other variable. We can declare an array of pointers but an array of references is not possible.

14. What do you mean by abstraction in C++?

Abstraction is the process of showing the essential details to the user and hiding the details which we don’t want to show to the user or hiding the details which are irrelevant to a particular user.

15. Is deconstructor overloading possible? If yes then explain and if no then why?

No destructor overloading is not possible. Destructors take no arguments, so there’s only one way to destroy an object. That’s the reason destructor overloading is not possible.

16. What do you mean by call by value and call by reference?

In call by value method, we pass a copy of the parameter is passed to the functions. For these copied values a new memory is assigned and changes made to these values do not reflect the variable in the main function.

In call by reference method, we pass the address of the variable and the address is used to access the actual argument used in the function call. So changes made in the parameter alter the passing argument.

17. What is an abstract class and when do you use it?

A class is called an abstract class whose objects can never be created. Such a class exists as a parent for the derived classes. We can make a class abstract by placing a pure virtual function in the class.

18. What are destructors in C++?

A constructor is automatically called when an object is first created. Similarly when an object is destroyed a function called destructor automatically gets called. A destructor has the same name as the constructor (which is the same as the class name) but is preceded by a tilde.

Example:

class A{
 private:
  int val;
 public:
  A(int x){           
   Val=x;
  }
  A(){                
  }
  ~A(){                  //destructor
  }
}
int main(){
 A a(3);     
 return 0;
}

19. What are the static members and static member functions?

When a variable in a class is declared static, space for it is allocated for the lifetime of the program. No matter how many objects of that class have been created, there is only one copy of the static member. So same static member can be accessed by all the objects of that class.

A static member function can be called even if no objects of the class exist and the static function are accessed using only the class name and the scope resolution operator ::

20. Explain inheritance

Inheritance is the process of creating new classes, called derived classes, from existing classes. These existing classes are called base classes. The derived classes inherit all the capabilities of the base class but can add new features and refinements of their own.

Example-

Inheritance_in_C__.Png?1614780459 Inheritance in C++

Class Bus, Class Car, and Class Truck inherit the properties of Class Vehicle.

The most important thing about inheritance is that it permits code reusability.

C++ Interview Questions For Experienced

21. What is a copy constructor?

A copy constructor is a member function that initializes an object using another object of the same class.

Example-

class A{
int x,y;
A(int x, int y){
 this->x=x;
 this->y=y;
}

};
int main(){
A a1(2,3);
A a2=a1;     //default copy constructor is called
return 0;
}

We can define our copy constructor. If we don’t define a copy constructor then the default copy constructor is called.

22. What is the difference between shallow copy and deep copy?

The difference between shallow copy and a deep copy is given below:

Shallow Copy Deep Copy Shallow copy stores the references of objects to the original memory address. Deep copy makes a new and separate copy of an entire object with its unique memory address. Shallow copy is faster. Deep copy is comparatively slower. Shallow copy reflects changes made to the new/copied object in the original object. Deep copy doesn’t reflect changes made to the new/copied object in the original object

23. What is the difference between virtual functions and pure virtual functions?

A virtual function is a member function in the base class that you redefine in a derived class. It is declared using the virtual keyword.

Example-

class base{
public:
 virtual void fun(){

 }
};

A pure virtual function is a function that has no implementation and is declared by assigning 0. It has no body.

Example-

class base{
public:
 virtual void fun()=0;
};

Here, = sign has got nothing to do with the assignment, and value 0 is not assigned to anything. It is used to simply tell the compiler that a function will be pure and it will not have anybody.

24. If class D is derived from a base class B. When creating an object of type D in what order would the constructors of these classes get called?

The derived class has two parts, a base part, and a derived part.  When C++ constructs derived objects, it does so in phases. First, the most-base class(at the top of the inheritance tree) is constructed. Then each child class is constructed in order until the most-child class is constructed last. 
So the first Constructor of class B will be called and then the constructor of class D will be called.

During the destruction exactly reverse order is followed. That is destructor starts at the most-derived class and works its way down to base class.
So the first destructor of class D will be called and then the destructor of class B will be called.

25. Can we call a virtual function from a constructor?

Yes, we can call a virtual function from a constructor. But the behavior is a little different in this case. When a virtual function is called, the virtual call is resolved at runtime. It is always the member function of the current class that gets called. That is the virtual machine doesn’t work within the constructor.

For example-

class base{
 private:
  int value;
 public:
  Base(int x){
   Value=x;
  }
  virtual void fun(){
   
  }
}

class derived{
 private:
  int a;
 public:
  Derived(int x, int y):base(x){
   Base *b;
   B=this;
   B->fun();      //calls derived::fun()
  }
  void fun(){
   cout<<”fun inside derived class”<<endl;
  }
}

26. What are void pointers?

A void pointer is a pointer which is having no datatype associated with it. It can hold addresses of any type.

For example-

void *ptr; 
char *str;
P=str;                // no error 
Str=p;                // error because of type mismatch

We can assign a pointer of any type to a void pointer but the reverse is not true unless you typecast it as

str=(char*) ptr;

27. What is this pointer in C++?

The member functions of every object have a pointer named this, which points to the object itself. The value of this is set to the address of the object for which it is called. It can be used to access the data in the object it points to.

Example

class A{
 private:
  int value;
 public:
  void setvalue(int x){
   this->value=x; 
  }
};

int main(){
 A a;
 A.Setvalue(5);
 return 0;
}

28. How do you allocate and deallocate memory in C++?

The new operator is used for memory allocation and deletes operator is used for memory deallocation in C++.

For example-

int value=new int;  		//allocates memory for storing 1 integer
delete value;          		// deallocates memory taken by value

int *arr=new int[10];    	//allocates memory for storing 10 int
delete []arr;              	// deallocates memory occupied by arr

Questions

1.

Which operator can not be overloaded in C++?

+

++
2.

What will be the output of the following C++ program:

#include<iostream>
using namespace std;
int main(){
int a=1;
cout<<(a++)*(++a)<<endl;
return 0;
}
1 6 2 3
3.

What will be the value of x in the following C++ program

#include<iostream>
using namespace std;
int main(){
int a=1;
int x=(a++)++;
cout<<x<<endl;
return 0;
}
Compile Time Error 3 1 2
4.

What is an abstract class?

Class declared with abstract keyword Class which has exactly one virtual function Class which hash at least one pure virtual function None of the above
5.

Consider the following C++ program

#include<iostream>
using namespace std;
class A{
public:
virtual void a()=0;
A(){
 cout<<"A ";
}
};
class B: public A
{
public:
B(){
 cout<<"B ";
} 
};

int main(){
A *a=new B();

return 0;
}

What will be output?

A B B A Compile-time error None of the above
6.

What is the size of void in C++?

0 1 2 4
7.

If a base class and derived class each include a member function with the same name. Function from which class will be called if called by an object of the derived class

Member function of the base class Member function of the derived class Depend on the parameter None of the above
8.

Memory used by an array is

Contiguous Non-contiguous Not determined None of the above
9.

Which of the following statement is correct?

An object is an instance of the class A friend function can access private members of a class Members of the class are private by default All of the above

DSA THAT WILL WE ASKED 100%

I started learning data structures and I am in arrays topic so I can solve  easy level and less medium level problems on arrays. Is it okay if I move  on to

BHAI ISS BAR 50 LAKH KI TOH LAG JEYEGI

ComplexityChart

DataStructureSelection

1.2 Vector std::vector

Use for

  • Simple storage
  • Adding but not deleting
  • Serialization
  • Quick lookups by index
  • Easy conversion to C-style arrays
  • Efficient traversal (contiguous CPU caching)

Do not use for

  • Insertion/deletion in the middle of the list
  • Dynamically changing storage
  • Non-integer indexing

Time Complexity

OperationTime Complexity
Insert HeadO(n)
Insert IndexO(n)
Insert TailO(1)
Remove HeadO(n)
Remove IndexO(n)
Remove TailO(1)
Find IndexO(1)
Find ObjectO(n)

Example Code

std::vector<int> v;

//---------------------------------
// General Operations
//---------------------------------

// Size
Unsigned int size = v.Size();

// Insert head, index, tail
V.Insert(v.Begin(), value);             // head
V.Insert(v.Begin() + index, value);     // index
V.Push_back(value);                     // tail

// Access head, index, tail
Int head = v.Front();       // head
Head = v[0];                // or using array style indexing

Int value = v.At(index);    // index
Value = v[index];           // or using array style indexing

Int tail = v.Back();        // tail
Tail = v[v.Size() - 1];     // or using array style indexing

// Iterate
For(std::vector<int>::iterator it = v.Begin(); it != v.End(); it++) {
    Std::cout << *it << std::endl;
}

// Remove head, index, tail
V.Erase(v.Begin());             // head
V.Erase(v.Begin() + index);     // index
V.Pop_back();                   // tail

// Clear
V.Clear();

1.3 Deque std::deque

Use for

  • Similar purpose of std::vector
  • Basically std::vector with efficient push_front and pop_front

Do not use for

  • C-style contiguous storage (not guaranteed)

Notes

  • Pronounced 'deck'
  • Stands for Double Ended Queue

Time Complexity

OperationTime Complexity
Insert HeadO(1)
Insert IndexO(n) or O(1)
Insert TailO(1)
Remove HeadO(1)
Remove IndexO(n)
Remove TailO(1)
Find IndexO(1)
Find ObjectO(n)

Example Code

std::deque<int> d;

//---------------------------------
// General Operations
//---------------------------------

// Insert head, index, tail
D.Push_front(value);                    // head
D.Insert(d.Begin() + index, value);     // index
D.Push_back(value);                     // tail

// Access head, index, tail
Int head = d.Front();       // head
Int value = d.At(index);    // index
Int tail = d.Back();        // tail

// Size
Unsigned int size = d.Size();

// Iterate
For(std::deque<int>::iterator it = d.Begin(); it != d.End(); it++) {
    Std::cout << *it << std::endl;
}

// Remove head, index, tail
D.Pop_front();                  // head
D.Erase(d.Begin() + index);     // index
D.Pop_back();                   // tail

// Clear
D.Clear();

1.4 List std::list and std::forward_list

Use for

  • Insertion into the middle/beginning of the list
  • Efficient sorting (pointer swap vs. Copying)

Do not use for

  • Direct access

Time Complexity

OperationTime Complexity
Insert HeadO(1)
Insert IndexO(n)
Insert TailO(1)
Remove HeadO(1)
Remove IndexO(n)
Remove TailO(1)
Find IndexO(n)
Find ObjectO(n)

Example Code

std::list<int> l;

//---------------------------------
// General Operations
//---------------------------------

// Insert head, index, tail
L.Push_front(value);                    // head
L.Insert(l.Begin() + index, value);     // index
L.Push_back(value);                     // tail

// Access head, index, tail
Int head = l.Front();                                           // head
Int value = std::next(l.Begin(), index);		        // index
Int tail = l.Back();                                            // tail

// Size
Unsigned int size = l.Size();

// Iterate
For(std::list<int>::iterator it = l.Begin(); it != l.End(); it++) {
    Std::cout << *it << std::endl;
}

// Remove head, index, tail
L.Pop_front();                  // head
L.Erase(l.Begin() + index);     // index
L.Pop_back();                   // tail

// Clear
L.Clear();

//---------------------------------
// Container-Specific Operations
//---------------------------------

// Splice: Transfer elements from list to list
//	splice(iterator pos, list &x)
//  	splice(iterator pos, list &x, iterator i)
//  	splice(iterator pos, list &x, iterator first, iterator last)
L.Splice(l.Begin() + index, list2);

// Remove: Remove an element by value
L.Remove(value);

// Unique: Remove duplicates
L.Unique();

// Merge: Merge two sorted lists
L.Merge(list2);

// Sort: Sort the list
L.Sort();

// Reverse: Reverse the list order
L.Reverse();

1.5 Map std::map and std::unordered_map

Use for

  • Key-value pairs
  • Constant lookups by key
  • Searching if key/value exists
  • Removing duplicates
  • std::map
    • Ordered map
  • std::unordered_map
    • Hash table

Do not use for

  • Sorting

Notes

  • Typically ordered maps (std::map) are slower than unordered maps (std::unordered_map)
  • Maps are typically implemented as binary search trees

Time Complexity

std::map

OperationTime Complexity
InsertO(log(n))
Access by KeyO(log(n))
Remove by KeyO(log(n))
Find/Remove ValueO(log(n))

std::unordered_map

OperationTime Complexity
InsertO(1)
Access by KeyO(1)
Remove by KeyO(1)
Find/Remove Value--

Example Code

std::map<std::string, std::string> m;

//---------------------------------
// General Operations
//---------------------------------

// Insert
M.Insert(std::pair<std::string, std::string>("key", "value"));

// Access by key
Std::string value = m.At("key");

// Size
Unsigned int size = m.Size();

// Iterate
For(std::map<std::string, std::string>::iterator it = m.Begin(); it != m.End(); it++) {
    Std::cout << (*it).First << " " << (*it).Second << std::endl;
}

// Remove by key
M.Erase("key");

// Clear
M.Clear();

//---------------------------------
// Container-Specific Operations
//---------------------------------

// Find if an element exists by key
Bool exists = (m.Find("key") != m.End());

// Count the number of elements with a certain key
Unsigned int count = m.Count("key");

1.6 Set std::set

Use for

  • Removing duplicates
  • Ordered dynamic storage

Do not use for

  • Simple storage
  • Direct access by index

Notes

  • Sets are often implemented with binary search trees

Time Complexity

OperationTime Complexity
InsertO(log(n))
RemoveO(log(n))
FindO(log(n))

Example Code

std::set<int> s;

//---------------------------------
// General Operations
//---------------------------------

// Insert
S.Insert(20);

// Size
Unsigned int size = s.Size();

// Iterate
For(std::set<int>::iterator it = s.Begin(); it != s.End(); it++) {
    Std::cout << *it << std::endl;
}

// Remove
S.Erase(20);

// Clear
S.Clear();

//---------------------------------
// Container-Specific Operations
//---------------------------------

// Find if an element exists
Bool exists = (s.Find(20) != s.End());

// Count the number of elements with a certain value
Unsigned int count = s.Count(20);

1.7 Stack std::stack

Use for

  • First-In Last-Out operations
  • Reversal of elements

Time Complexity

OperationTime Complexity
PushO(1)
PopO(1)
TopO(1)

Example Code

std::stack<int> s;

//---------------------------------
// Container-Specific Operations
//---------------------------------

// Push
S.Push(20);

// Size
Unsigned int size = s.Size();

// Pop
S.Pop();

// Top
Int top = s.Top();

1.8 Queue std::queue

Use for

  • First-In First-Out operations
  • Ex: Simple online ordering system (first come first served)
  • Ex: Semaphore queue handling
  • Ex: CPU scheduling (FCFS)

Notes

  • Often implemented as a std::deque

Example Code

std::queue<int> q;

//---------------------------------
// General Operations
//---------------------------------

// Insert
Q.Push(value);

// Access head, tail
Int head = q.Front();       // head
Int tail = q.Back();        // tail

// Size
Unsigned int size = q.Size();

// Remove
Q.Pop();

1.9 Priority Queue std::priority_queue

Use for

  • First-In First-Out operations where priority overrides arrival time
  • Ex: CPU scheduling (smallest job first, system/user priority)
  • Ex: Medical emergencies (gunshot wound vs. Broken arm)

Notes

  • Often implemented as a std::vector

Example Code

std::priority_queue<int> p;

//---------------------------------
// General Operations
//---------------------------------

// Insert
P.Push(value);

// Access
Int top = p.Top();  // 'Top' element

// Size
Unsigned int size = p.Size();

// Remove
P.Pop();

1.10 Heap std::priority_queue

Notes

  • A heap is essentially an instance of a priority queue
  • min heap is structured with the root node as the smallest and each child subsequently larger than its parent
  • max heap is structured with the root node as the largest and each child subsequently smaller than its parent
  • A min heap could be used for Smallest Job First CPU Scheduling
  • A max heap could be used for Priority CPU Scheduling

Max Heap Example (using a binary tree)

MaxHeap

2.0 Trees

2.1 Binary Tree

  • A binary tree is a tree with at most two (2) child nodes per parent
  • Binary trees are commonly used for implementing O(log(n)) operations for ordered maps, sets, heaps, and binary search trees
  • Binary trees are sorted in that nodes with values greater than their parents are inserted to the right, while nodes with values less than their parents are inserted to the left

Binary Search Tree

BinarySearchTree

2.2 Balanced Trees

  • Balanced trees are a special type of tree which maintains its balance to ensure O(log(n)) operations
  • When trees are not balanced the benefit of log(n) operations is lost due to the highly vertical structure
  • Examples of balanced trees:
    • AVL Trees
    • Red-Black Trees

2.3 Binary Search

Idea:

  1. If current element, return
  2. If less than current element, look left
  3. If more than current element, look right
  4. Repeat

Data Structures:

  • Tree
  • Sorted array

Space:

  • O(1)

Best Case:

  • O(1)

Worst Case:

  • O(log n)

Average:

  • O(log n)

Visualization:

BinarySearch

2.4 Depth-First Search

Idea:

  1. Start at root node
  2. Recursively search all adjacent nodes and mark them as searched
  3. Repeat

Data Structures:

  • Tree
  • Graph

Space:

  • O(V)V = number of verticies

Performance:

  • O(E)E = number of edges

Visualization:

DepthFirstSearch

2.5 Breadth-First Search

Idea:

  1. Start at root node
  2. Search neighboring nodes first before moving on to next level

Data Structures:

  • Tree
  • Graph

Space:

  • O(V)V = number of verticies

Performance:

  • O(E)E = number of edges

Visualization:

DepthFirstSearch

3.0 NP Complete Problems

3.1 NP Complete

  • NP Complete means that a problem is unable to be solved in polynomial time
  • NP Complete problems can be verified in polynomial time, but not solved

3.2 Traveling Salesman Problem


3.3 Knapsack Problem

Implementation


4.0 Algorithms

4.1 Insertion Sort

Idea

  1. Iterate over all elements
  2. For each element:
    • Check if element is larger than largest value in sorted array
  3. If larger: Move on
  4. If smaller: Move item to correct position in sorted array

Details

  • Data structure: Array
  • Space: O(1)
  • Best Case: Already sorted, O(n)
  • Worst Case: Reverse sorted, O(n^2)
  • Average: O(n^2)

Advantages

  • Easy to code
  • Intuitive
  • Better than selection sort and bubble sort for small data sets
  • Can sort in-place

Disadvantages

  • Very inefficient for large datasets

Visualization

InsertionSort

4.2 Selection Sort

Idea

  1. Iterate over all elements
  2. For each element:
    • If smallest element of unsorted sublist, swap with left-most unsorted element

Details

  • Data structure: Array
  • Space: O(1)
  • Best Case: Already sorted, O(n^2)
  • Worst Case: Reverse sorted, O(n^2)
  • Average: O(n^2)

Advantages

  • Simple
  • Can sort in-place
  • Low memory usage for small datasets

Disadvantages

  • Very inefficient for large datasets

Visualization

SelectionSort

SelectionSort

4.3 Bubble Sort

Idea

  1. Iterate over all elements
  2. For each element:
    • Swap with next element if out of order
  3. Repeat until no swaps needed

Details

  • Data structure: Array
  • Space: O(1)
  • Best Case: Already sorted O(n)
  • Worst Case: Reverse sorted, O(n^2)
  • Average: O(n^2)

Advantages

  • Easy to detect if list is sorted

Disadvantages

  • Very inefficient for large datasets
  • Much worse than even insertion sort

Visualization

BubbleSort

4.4 Merge Sort

Idea

  1. Divide list into smallest unit (1 element)
  2. Compare each element with the adjacent list
  3. Merge the two adjacent lists
  4. Repeat

Details

  • Data structure: Array
  • Space: O(n) auxiliary
  • Best Case: O(nlog(n))
  • Worst Case: Reverse sorted, O(nlog(n))
  • Average: O(nlog(n))

Advantages

  • High efficiency on large datasets
  • Nearly always O(nlog(n))
  • Can be parallelized
  • Better space complexity than standard Quicksort

Disadvantages

  • Still requires O(n) extra space
  • Slightly worse than Quicksort in some instances

Visualization

MergeSort

MergeSort

4.5 Quicksort

Idea

  1. Choose a pivot from the array
  2. Partition: Reorder the array so that all elements with values less than the pivot come before the pivot, and all values greater than the pivot come after
  3. Recursively apply the above steps to the sub-arrays

Details

  • Data structure: Array
  • Space: O(n)
  • Best Case: O(nlog(n))
  • Worst Case: All elements equal, O(n^2)
  • Average: O(nlog(n))

Advantages

  • Can be modified to use O(log(n)) space
  • Very quick and efficient with large datasets
  • Can be parallelized
  • Divide and conquer algorithm

Disadvantages

  • Not stable (could swap equal elements)
  • Worst case is worse than Merge Sort

Optimizations

  • Choice of pivot:
    • Choose median of the first, middle, and last elements as pivot
    • Counters worst-case complexity for already-sorted and reverse-sorted

Visualization

QuickSort

AGAR TERE KO FAANG NIKALANA HAI TOH YE SAB KARLE TAMIZ SE ,

1. Can you tell us about yourself?
Answer: This is usually the first question asked in an interview. Start by briefly summarizing your education, experience, and any relevant qualifications. Highlight any achievements or accomplishments that make you a good fit for the role.

2. Why do you want to work for our company?
Answer: Research the company beforehand and find specific reasons why you want to work there. Mention the company's values, mission, and culture, and how they align with your own career goals and aspirations.

3. What are your greatest strengths?
Answer: Talk about your strengths that are relevant to the job. Provide specific examples of how you have used these strengths in past experiences and how they will be useful in the new role.

4. What are your greatest weaknesses?
Answer: Be honest but don't focus on weaknesses that are critical for the job. Instead, discuss a weakness that you have been working on and mention steps you are taking to improve.

5. Can you give an example of a time when you overcame a difficult challenge?
Answer: Choose a challenging situation from your past experiences and explain how you tackled the problem. Highlight your problem-solving skills and how you managed to overcome the obstacle.

6. Where do you see yourself in five years?
Answer: Be realistic but also show that you are ambitious. Talk about how you hope to develop your skills and career, and how the job you are interviewing for can help you achieve your goals.

7. Why should we hire you?
Answer: Summarize your skills and experiences that make you the ideal candidate for the job. Provide examples of your achievements and how they will be useful in the new role.

8. How do you handle stress and pressure?
Answer: Explain how you manage stress and pressure in the workplace. Provide examples of situations where you have been under pressure and how you dealt with it.

9. Do you have any questions for us?
Answer: Always prepare a few questions to ask the interviewer. These could be about the company culture, the job responsibilities, or any specific challenges you might face in the role. It shows that you are interested and engaged in the job.

YE HAI SAB KA NICHOD........!!!!

deque_crop.Png

TU PHODEGA ......!!!!

JAA FATEH HASIL KAR MERE YAAR......!!!!

Entradas relacionadas: