0% found this document useful (0 votes)
8 views23 pages

c & data structure

A computer is an electronic device that processes input data according to programmed instructions to produce output and store results. The CPU, consisting of the ALU, memory unit, and control unit, performs data processing and controls operations. The document also covers programming concepts in C, including data types, operators, control structures, and arrays, providing examples and explanations for each topic.

Uploaded by

Jyothi S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views23 pages

c & data structure

A computer is an electronic device that processes input data according to programmed instructions to produce output and store results. The CPU, consisting of the ALU, memory unit, and control unit, performs data processing and controls operations. The document also covers programming concepts in C, including data types, operators, control structures, and arrays, providing examples and explanations for each topic.

Uploaded by

Jyothi S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

What is a Computer?

Computer is an advanced electronic device that takes raw data as an input from the user and processes
it under the control of a set of instructions (called program), produces a result (output), and saves it for
future use

Functionalities :

 Step 1 − Takes data as input.


 Step 2 − Stores the data/instructions in its memory and uses them as required.
 Step 3 − Processes the data and converts it into useful information.
 Step 4 − Generates the output.

CPU (Central Processing Unit): CPU is considered as the brain of the computer. CPU performs all
types of data processing operations. It stores data, intermediate results, and instructions
(program). It controls the operation of all parts of the computer. CPU itself has the following
three components –
 ALU (Arithmetic Logic Unit) ---All types of processing, such as comparisons, decision-making
and processing of non-numeric information takes place here and once again data is moved to
RAM.
 Memory Unit ---This is unit in which data and instructions given to computer as well as results
given by computer are stored. Unit of memory is "Byte". 1 Byte = 8 Bits
 Control Unit---- CPU extracts instructions, performs execution, maintains and directs
operations of entire system.
Functions of Control Unit Control unit performs following functions –
 It controls all activities of computer  Supervises flow of data within CPU  Directs flow of data
within CPU  Transfers data to Arithmetic and Logic Unit  Transfers results to memory  Fetches
results from memory to output devices

 In a C program, single-line comments can be written using two forward slashes i.e., //,
and we can create multiline comments using /* */.
 Global Declaration This section includes all global variables, function declarations, and
static variables. The variables declared in this section can be used anywhere in the
program. They're accessible to all the functions of the program. Hence, they are called
global variables
 Main() Function In the structure of a C program, this section contains the main function
of the code. The compiler starts execution from the main() function. It can use global
variables, static variables, inbuilt functions, and user-defined functions. The return type
of the main() function can be void and also not necessarily int.
 Elements of C Programming Language
 Character Set in C Language Type Set
 Lowercase a-z
 Uppercase A-Z
 Digits 0-9
 special characters !,@,#,$,%
 White space space, tab, and new lines
 Keywords: 1) they are those elements of C language whose meaning has already being
defined or explained. 2) keyword are called pre-defined words. 32 keywords in C
language
 Auto, Do, Goto, Break Void ,Else ,Int ,Case, Double ,Sizeof ,Enum ,Long,If, While,,For ,
Const, Volatile, Float, Return ,Union, Const,

 signed, unsigned, static, struct ,char ,extern ,register, continue, default, typeodef, short
 Variables: It is the most fundamental aspect of any language. It is a location in the
Computer memory which can store value and is a given symbolic name for easy
reference. Variable declaration requires that you inform c of the variable's name and
date data types. Example: int page_no; char grade; float salary;
 int page-no=10; char grade='A'; float salary= 1200.50; int a=10, b=20, c=30;
 Expressions: An expression consist of combination of operands, operators, variables and
functions calls. An expression can be arithmetic, logical, or relational. Example of
Expressions: a+b=c [arithmetic operation] a>b [relational operation] a==b [logical
operations] func(a,b) [function calls]
 Statement: A statement is a complete instruction to the computer. In C, statements are
indicated by semicolon ; at the end. Example: legs =4; it is a statement. legs=4 it is an
expression.
 What is algorithm?
 An algorithm is a procedure or step-by-step instruction for solving a problem. They form
the foundation of writing a program.
 Step 1: Start Step
 2: Declare variables num1, num2 and sum.
 Step 3: Read values num1 and num2.
 Step 4: Add num1 and num2 and assign the result to sum. sum←num1+num2
 Step 5: Display sum
 Step 6: Stop
 For writing any programs, the following has to be known:  Input  Tasks to be
preformed  Output expected
 Flowchart: Flowchart is a diagrammatic representation of sequence of logical steps of a
program. Flowcharts use simple geometric shapes to depict processes and arrows to
show relationships and process/data flow.

Start/Stop


Process

Input/output Onpage
connector use
 numbers

decision

Off page connector


Shows uses alphabets
relation
ships

 Integer Types:
 The integer data type in C is used to store the whole numbers without decimal values.
Octal values, hexadecimal values, and decimal values can be stored in int data type in C
 Size: 2 bytes or 4 bytes  Format Specifier: %d
 Character Types Character data type allows its variable to store only a single character.
  Size: 1 byte  Format Specifier: %c
 Floating-Point Types In C programming float data type is used to store floating-point
values. Float in C is used to store decimal and exponential values. It is used to store
decimal numbers (numbers with floating point values) with single precision.
  Size: 4 bytes  Format Specifier: %f
 Arithmetic Operators: An arithmetic operator performs mathhematical operations such
as addition, subtraction, multiplication, division etc on numerical values (constants and
variables).
 + addition or unary plus - subtraction or unary minus * Multiplication / division %
remainder after division (modulo division)
 Example 1: Arithmetic Operator
 // Working of arithmetic operators
 #include <stdio.h>
 int main()
 {
 int a = 9,b = 4, c;
 c = a+b;
 printf("a+b = %d \n",c);
 c = a-b;
 printf("a-b = %d \n",c);
 c = a*b;
 printf("a*b = %d \n",c);
 c = a/b;
 printf("a/b = %d \n",c);
 c = a%b;
 printf("Remainder when a divided by b = %d \n",c);
 return 0;
 }
 Output
 a+b=13 a-b = 5 a*b = 36 a/b = 2
 Increment and Decrement Operators: C programming has two operators increment ++
and decrement -- to change the value of an operand (constant or variable) by 1.
 Assignment Operators: An assignment operator is used for assigning a value to a
variable. The most common assignment operator is =
 += a += b a = a+b
 -= a -= b a = a-b
 *= a *= b a = a*b
 /= a /= b a = a/b
 %= a %= b a = a%b
 Relational Operators : Equal to
 Greater than
 Less than
 != Not equal to
 >= Greater than or equal to
 <= Less than or equal to
 Logical Operators An expression containing logical operator returns either 0 or 1
depending upon whether expression results true or false. Logical operators are
commonly used in decision making in C programming
 Logical AND, Logical OR, Logical NOT
 Control Structures :: control the flow of execution in a program.
 1. Decision making/Conditional/Branching/sectional Statements
 1. Simple if 2. if-else 3. if-else-if ladder 4. nested if 5. Switch
1. simple if:
2. The syntax :
3. If (condition1) {
4. Body of if statement;
5. }
6. Next statement;
7. Program:
8. include <stdio.h>
9. int main ()
10.{
11.int a = 10;
12.if( a < 20 )
13.{
14.printf("a is less than 20\n" );
15.}
16.printf("value of a is : %d\n", a);
17.return 0;
18.}
19.e If… Else Statement:
20.If (condition 1) { Statement 1 ; } else { Statement 2 ; } Next Statement;
21.Program: #include<stdio.h>
22.void main()
23.{ i
24.nt num1, num2;
25.printf("Please Enter Two different values\n"); s
26.canf("%d %d", &num1, &num2);
27.if(num1 > num2) { printf("%d is Largest\n", num1);
28.}
29.else { printf("%d is Largest\n", num2);
30.}
31.}
32. Switch Statements:
33.Switch (expression_A) { case_A: Statement 1; break; case_B: Statement 2 ; break; case_C;
Statement 3 ; break; …. case_Z: Statement N; break; Default: Default Statement; break; } Next
statement;
34.
35.
 2. Looping Statements/Iterative Statements
 WHILE LOOP- Repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body
 #include<stdio.h>
 int main ()
{
 /* local variable definition */
 int a = 10; /
 * while loop execution */
 while( a < 20 )
 { printf("value of a: %d\n", a);
 a++;
 }
 return 0;
 }

 FOR LOOP- Executes a sequence of statements multiple times and abbreviates the code
that manages the loop variable.

#include <stdio.h>

int main ()

int a;

/* for loop execution */

for( a = 10;

a < 20;

a=a+1)

printf("value of a: %d\n", a);

return 0;

 DO—WHILE”” It is more like a while statement, except that it tests the condition at the
end of the loop body.
 #include<stdio.h>
 int main ()
 {
 /* local variable definition */
 int a = 10;
 /* do loop execution */
 Do
 {
 printf("value of a: %d\n", a);
 a = a + 1;
 }
 while( a < 20 );
 return 0;
 }

 NESTED LOOPS You can use one or more loops inside any other while, for, or do..while
loop.
 3. Jump Statements/Loop control statements
 break statement Terminates the loop or switch statement and transfers execution to
the statement immediately following the loop or switch.
 continue statement Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
 goto statement Transfers control to the labeled statement.
 #include<stdio.h>
 int main ()
 {
 /* local variable definition */
 int a = 10;
 while( a < 20 )
 {
 printf("value of a: %d\n", a);
 a++;
 if( a > 15)
 {
 /* terminate the loop using break statement */ break;
 }
 }
 return 0;
 Output: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of
a: 15
 continue statement:
 The continue statement in C programming works somewhat like the break statement.
Instead of forcing termination, it forces the next iteration of the loop to take place,
skipping any code in between.

Array::
 collection of similar type of data items stored at contiguous memory locations. Arrays are the
derived data type in C programming language which can store the primitive type of data such as
int, char, double, float, etc. It also has the capability to store the collection of derived data types,
such as pointers, structure, etc. The array is the simplest data structure where each data
element can be randomly accessed by using its index number.
 For example, if we want to store the marks of a student in 6 subjects, then we don't need to
define different variables for the marks in the different subject. Instead of that, we can define an
array which can store the marks in each subject at the contiguous memory locations.
 Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
 Elements of the array are stored at contiguous memory locations where the first element is
stored at the smallest memory location.
 Elements of the array can be randomly accessed since we can calculate the address of each
element of the array with the given base address and the size of the data element.
 Advantage of C Array:
 1) Code Optimization: Less code to the access the data.
 2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
 3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
 4) Random Access: We can access any element randomly using the array
 Disadvantage of C Array: 1) Fixed Size: Whatever size, we define at the time of declaration of
the array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which
we will learn later.
 Types of Arrays:
 Arrays can be classified into types:
 1.One dimensional array 2
 The one-dimensional array can be defined as a sequential collection of elements. The 1D array is
also called as linear array.
 Declaration of C Array We can declare an array in the c language in the following way.
 data_type array_name[array_size];
 Now, let us see the example to declare the array.
 int marks[5];
 Here, int is the data_type, marks are the array_name, and 5 is the array_size.

The simplest way to initialize an array is by using the index of each element.

We can initialize each element of the array by using the index.

Consider the following example.

1. marks[0]=80; 2. marks[1]=60; 3. marks[2]=70; 4. marks[3]=85; 5. marks[4]=75;

80 60 70 85 75
Marks[0] Marks[1] Marks[2] Marks[3] Marks[4]
int marks[]={20,30,40,50,60};
Let's see the C program to declare and initialize the array in C
#include<stdio.h>
int main()
{
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
for(i=0;i<5,i++)
{
Printf(“%d\n “,marks[n]);
}
return 0;
}

Declaration with Initialization We can initialize the c array at the time of declaration. Let's see
the code. 1. int marks[5]={20,30,40,50,60}; In such case, there is no requirement to define the
size. So it may also be written as the following code. 1. int marks[]={20,30,40,50,60}; Let's see
the C program to declare and initialize the array in C

 Two Dimensional Array: The two-dimensional array can be defined as an array of arrays.
The 2D array is organized as matrices which can be represented as the collection of rows
and columns.
 e. It provides ease of holding the bulk of data at once which can be passed to any
number of functions wherever required
 data_type array_name[rows][columns];
 int twodimen[4][3];
 int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
arr[0][0] = 1
 4 is the number of rows, and 3 is the number of columns arr[0][1] = 2
 Two-dimensional array example in C arr[0][2] = 3
arr[1][0] = 2
 arr[1][1] = 3
 #include<stdio.h> arr[1][2] = 4
 int main() arr[2][0] = 3
 { arr[2][1] = 4
arr[2][2] = 5
 int i=0,j=0;
arr[3][0] = 4
 int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; arr[3][1] = 5
 for(i=0;i<4;i++) arr[3][2] =
 {
 For(j=0;j<3;j++;)
 {
 printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
 }
 }
 Return 0;
 }

Functions:

 In c, we can divide a large program into the basic building blocks known as function.
 A function can be called multiple times to provide reusability and modularity to the C program
 The function is also known as procedure or subroutine in other programming languages.
 Advantage :: we can avoid rewriting same logic/code again and again in a program.
 We can call C functions any number of times in a program and from any place in a program
 Reusability is the main achievement of C functions
 Function declaration ::A function must be declared globally in a c program to tell the compiler
about the function name, function parameters, and return type.
 Function call Function ::can be called from anywhere in the program. The parameter list must
not differ in function calling and function declaration. We must pass the same number of
functions as it is declared in the function declaration.
 Function definition It contains the actual statements which are to be executed. It is the most
important aspect to which the control comes when the function is called. Here, we must notice
that only one value can be returned from the function.
 Library Functions: are the functions which are declared in the C header files such as
 scanf(), printf(), gets(), puts(), ceil(), floor() etc.
 User-defined functions: are the functions which are created by the C programmer, so that
he/she can use it many times. It reduces the complexity of a big program and optimizes the code

CALL BY VALUE AND CALL BY REFERENCE

In c there are two methods to pass the data into the function in c language, i.e.,

 call by value and call by reference.


 Call by value in C:: the value of the actual parameters is copied into the formal parameters. In
other words, we can say that the value of the variable is used in the function call in the call by
value method.
 #include <stdio.h>
 void change(int num)
{
 printf("Before adding value inside function num=%d \n",num);
 num=num+100;
 printf("After adding value inside function num=%d \n", num);
}
 int main()
{ Output

 int x=100; Before function call x=100

 printf("Before function call x=%d \n", x); Before adding value inside function num=100
 change(x);//passing value in function After adding value inside function num=200
 printf("After function call x=%d \n", x); After function call x=100
 return 0;
}
 Call by Value Example: Swapping the values of the two variables
 #include <stdio.h> Before swapping the values in main a =
 void swap(int , int); //prototype of the function 10, b = 20
 int main() After swapping values in function a = 20,
{ b = 10

 int a = 10; After swapping values in main a = 10, b =


20
 int b = 20;
 printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a
and b in main
 swap(a,b);
 printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual
parameters do not change b y changing the formal parameters in call by value, a = 10, b = 20
}
 void swap (int a, int b)
{
 int temp;
 temp = a;
 a=b;
 b=temp;
 printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a =
20, b = 10
}
 CALL BY REFERENCE ::
 the address of the variable is passed into the function call as the actual parameter.

 In call by reference, the memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed on the value stored at the
address of the actual parameters, and the modified value gets stored at the same address.
 #include <stdio.h>

 void change(int *num)


Before function call x=100
 {
Before adding value inside function
 printf("Before adding value inside function num=%d \n",*num); num=100

 (*num) += 100; After adding value inside function


num=200
 printf("After adding value inside function num=%d \n", *num);
After function call x=200
 }

 int main()

 {

 int x=100;

 printf("Before function call x=%d \n", x);

 change(&x);//passing reference in function

 printf("After function call x=%d \n", x);

 return 0;

 }
 CALL BY REFERENCE EXAMPLE: SWAPPING THE VALUES OF THE TWO VARIABLES

 #include <stdio.h>

 void swap(int *, int *); //prototype of the function Before swapping the values in main
 int main() a = 10, b = 20

 {
After swapping values in function a
= 20, b = 10
 int a = 10;
After swapping values in main a =
 int b = 20; 20, b = 10

 printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the


value of a and b in main
 swap(&a,&b);

 printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual


parameters do change in c all by reference, a = 10, b = 20
 }

 void swap (int *a, int *b)

 {

 int temp;

 temp = *a;

 *a=*b;

 *b=temp; printf("After swapping values in function a = %d, b = %d\n",*a,*b); //


Formal parameters, a = 20, b = 10
 }

Call by value Call by reference


 A copy of the value is passed into the  An address of value is passed into the
function function
 Changes made inside the function is  Changes made inside the function
limited to the function only. The values of validate outside of the function also. The
the actual parameters do not change by values of the actual parameters do
changing the formal parameters. change by changing the formal
 Actual and formal arguments are created
parameters.
at the different memory location  Actual and formal arguments are created
at the same memory location
RECURSION IN C::
 Any function which calls itself is called recursive function, and such function calls are called
recursive calls.

 recursion may be applied to sorting, searching, and traversal problems.

 tower of Hanoi, Fibonacci series, factorial finding

 In the following example, recursion is used to calculate the factorial of a number.

 #include<stdio.h>

 int fact (int);

 int main()

 {

 int n,f;

 printf("Enter the number whose factorial you want to calculate?");

 scanf("%d",&n);

 f = fact(n);

 printf("factorial = %d",f);

 }

 int fact(int n)

 {

 if (n==0)
nter the number whose factorial you
 { want to calculate?5 factorial = 120

 return 0;

 }

 else if ( n == 1)

 {

 return 1;

 }
 else

 {

 return n*fact(n-1);

 }

 }

POINTERS: The pointer in C language is a variable which stores the address of another variable.
This variable can be of type int, char, array, function, or any other pointer

 int n = 10;

 int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.

 malloc() allocates single block of requested memory.-- It returns NULL if memory is not sufficient

 calloc() allocates multiple block of requested memory- It initially initialize all bytes to zero. It
returns NULL if memory is not sufficient

 realloc() reallocates the memory occupied by malloc() or calloc() functions.- If memory is not
sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it
changes the memory size

 free() frees the dynamically allocated memory- The memory occupied by malloc() or calloc()
functions must be released by calling free() function. Otherwise, it will consume memory until
program exit.

 Pointer Expressions

 Structures Arrays allow to define type of variables that can hold several data items of the same kind.

 To define a structure, you must use the struct statement.

 Union A union is a user defined data type available in C that allows to store different data types in
the same memory location.

 To define a union, you must use the union statement in the same way as you did while defining a
structure

 C Strings  The string can be defined as the one-dimensional array of characters terminated by a null
('\0'). The character array or the string is used to manipulate text such as word or sentences.
 Difference between char array and string literal: There are two main differences between char array
and literal. o We need to add the null character '\0' at the end of the array by ourself whereas, it is
appended internally by the compiler in the case of the character array

 gets() and puts() functions:

 gets() function: The gets() function enables the user to enter some characters followed by the enter
key. All the characters entered by the user get stored in a character array. The null character is
added to the array to make it a string. The gets() allows the user to enter the space-separated
strings.

 puts() function: The puts() function is very much similar to printf() function. The puts() function is
used to print the string on the console which is previously read by using gets() or scanf() function

 String Functions;;
 1) strlen(string_name) returns the length of string name.

 2) strcpy(destination, source) copies the contents of source string to destination string.

 3) strcat(first_string, second_string) concats or joins first string with second string. The result of
the string is stored in first string.

 4) strcmp(first_string, second_string) compares the first string with second string. If both strings are
same, it returns 0.

 5) strrev(string) returns reverse string.

 6) strlwr(string) returns string characters in lowercase.

 7) strupr(string) returns string characters in uppercase.

DATA STRUCTURES?
 Data Structure can be defined as the group of data elements which provides an
efficient way of storing and organising data in the computer so that it can be
used efficiently.
 Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc.
Data Structures are widely used in almost every aspect of Computer Science i.e.
Operating System, Compiler Design, Artifical intelligence, Graphics and many
more.
 Linear Data Structures:: A data structure is called linear if all of its elements are
arranged in the linear order. In linear data structures, the elements are stored in
non-hierarchical way where each element has the successors and predecessors
except the first and last element.
 Arrays: An array is a collection of similar type of data items and each data item
is called an element of the array. The data type of the element may be any valid
data type like char, int, float or double
 Stack:: A Stack is a linear data structure that follows the LIFO (Last-In-First-Out)
principle.
 Stack has one end, whereas the Queue has two ends (front and rear). It contains
only one pointer top pointer pointing to the topmost element of the stack.
 Whenever an element is added in the stack, it is added on the top of the stack,
and the element can be deleted only from the stack.
 In other words, a stack can be defined as a container in which insertion and
deletion can be done from the one end known as the top of the stack.
The following are some common operations implemented on the stack:
 push(): When we insert an element in a stack then the operation is known as a push. If the stack
is full then the overflow condition occurs. - we initialize a stack, we set the value of top as -1
or NULL to check that the stack is empty. top=top+1, and the element will be placed at the new
position of the top


 pop(): When we delete an element from the stack, the operation is known as a pop. If the stack
is empty means that no element exists in the stack, this state is known as an underflow state. -
> top=top-1.


 isEmpty(): It determines whether the stack is empty or not.
 isFull(): It determines whether the stack is full or not.'
 peek(): It returns the element at the given position.
 count(): It returns the total number of elements available in a stack.
 change(): It changes the element at the given position.
 display(): It prints all the elements available in the stack.

 Arithmetic Expression Evaluation::


 Infix notation, in which each operator is written between two operands (i.e., A + B)
 prefix notation, the operator is placed after its two operands +AB
 postfix notation, in which the operator is placed after its two operands AB+
 PRECEDENCE::
 Highest: Exponentiation (^)
 Next highest: Multiplication (*) and division (/)
 Lowest: Addition (+) and Subtraction (-)
(A-B)*[C/(D+E)+F]
AB-CDE+/F+*
Infix Expression: A+
(B*C-(D/E^F)*G)*H
A(B*C(D/E^F)G*-H*+
ABC*(D/E^F)G*-H*+

ABC*DE^F^/G*-H*+

SYMBO SCANNE STACK POSTFI DESCRIPTION


L D X EXP
1 ( START
2 A ( A
3 + (+ A
4 ( (+( A
5 B (+( AB
6 * (+(* AB
7 C (+(* ABC
8 - (+(- ABC* *higher
precedenc
e than -
9 ( (+(-(
10 D (+(-
11 / (+(-/
12 E (+(-/
13 ^ (+(-^
14 A
15 )
16 *
17 G
18 )
19 *
20 H
21 ) EMPT
Y

Sorting Algorithms::
1.Selection Sort – ( complexity in all cases o(n2))
2. selects the smallest (or largest) element from the unsorted portion
of the list and swaps it with the first element of the unsorted part.
3. arr[] = {64, 25, 12, 22, 11}
4. index 0,1,2,3,4

 {64, 25, 12, 22, 11}


 11,25,12,22,64 swap 11 and 64
 11,12,25,22,64 swap 12 and 25
 11,12,22,25,64 swap 22 and 25

Bubble Sort –repeatedly swapping the adjacent elements if they


are in the wrong order.
( complexity in all cases o(n2))
 Total no. of passes: n-1
 Total no. of comparisons: n*(n-1)/2

Input: arr[] = {6, 3, 0, 5}


First pass:
1.6,3,0,5
2.3,6,0,5
3.3,0,5,6
Second pass:

1.3,0,5,6
2.0,3,5,6
Third pass :: 1.check the final sorted list

Insertion Sort:: arr[]: {12, 11, 13, 5, 6}


Best case o(n)

Avg worst o(n2)

1.12,11,13,5,6

2.11,12,13,5,6 first two elements are sorted

3.11,12,13,5,6 then next to two elements

4.11,12,13,5,6 compare 13,5

5.11,12,5,13,6 12 and 5 are not sorted then swap

6.11,5,12,13,6 11,5 are not sorted then swap

7.5,11,12,13,6 array is not sorted

8.5,11,12,6,13

9.5,11,6,12,13

10.5,6,11,12,13 complete sorted array

Merge Sort
Complexity in all cases o(n log n)

divide the array into two halves, sort each half, and then merge the sorted
halves back together.

arr[] = {38, 27, 43, 10}


1. 38, 27 43, 10 divide in to two parts
2.38 27 (divide and swap bcz single element) 43 10 divide and swap
3.27,38 swap 10,43 swap
4.merging sorted sub arrays
27,38,10,43

QuickSort Divide and Conquer algorithm that picks an element as


a pivot and partitions the given array around the picked pivot by placing
the pivot in its correct position in the sorted array.

Complexity in avg and avg case o(n log n)


Worst case o(n2)
arr[] = {10, 80, 30, 90, 40}. Pivot value = 40
 10,80,30,90,40
 Compare 10 with the pivot and as it is less than pivot arrange it
accrodingly.

 Compare 80 with the pivot. It is greater than pivot.


 10,80,30,90,40
 10,30,80,90,40 compare 30
 Compare 90 with the pivot. It is greater than the pivot.
 10,30,80,40,90
 10,30,40,80,90

Heap Sort comparison-based sorting technique based on Binary


Heap data structure
arr[] = {4, 10, 3, 5, 1}.
Build Complete Binary Tree: Build a complete binary tree from the array.
Algorithm Time Complexity Space Complexity

Best Average Worst Worst

Selection Sort Ω(n^2) θ(n^2) O(n^2) O(1)

Bubble Sort Ω(n) θ(n^2) O(n^2) O(1)

Insertion Sort Ω(n) θ(n^2) O(n^2) O(1)

Heap Sort Ω(n log(n)) θ(n log(n)) O(n log(n)) O(1)

Merge Sort Ω(n log(n)) θ(n log(n)) O(n log(n)) O(n)

O(n)
Quick Sort Ω(n log(n)) θ(n log(n)) O(n2))

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy