12thdecACA

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Date: 12-12-2024

7 Sorting
7.1 Insertion Sort
Algorithm:
1. Iterate through the array from the second element to the last element.
2. For each element, store its value in a temporary variable.
3. Compare the temporary value with elements in the sorted portion of the array (elements to its left):

• Shift larger elements one position to the right.


4. Insert the temporary value into its correct position in the sorted portion.
5. Repeat until the entire array is sorted.

Time Complexity:
• Best Case: O(n): When the array is already sorted, only n − 1 comparisons are needed.
• Worst Case: O(n2 ): When the array is sorted in reverse order, the inner loop runs for every element.
• Average Case: O(n2 ): On average, elements are halfway out of place.

Space Complexity:
• O(1): Sorting is done in-place, requiring no extra memory.
Code:
# include < iostream >
# include < vector >
using namespace std ;

void insertionSort ( vector < int >& arr )


{
int n = arr . size () ;
for ( int i = 1; i < n ; i ++)
{
int key = arr [ i ];
int j = i - 1;

while ( j >= 0 && arr [ j ] > key )


{
arr [ j + 1] = arr [ j ];
j - -;
}
arr [ j + 1] = key ;
}
}

int main ()
{
int n ;
cout << " Enter the number of elements : " ;
cin >> n ;

vector < int > arr ( n ) ;


cout << " Enter the elements : " ;
for ( int i = 0; i < n ; i ++)
cin >> arr [ i ];

insertionSort ( arr ) ;

cout << " Sorted array : " ;


for ( int num : arr )
cout << num << " " ;

42
cout << endl ;
return 0;
}

Output 1:
Enter the number of elements: 5
Enter the elements: 12 11 13 5 6
Sorted array: 5 6 11 12 13
Output 2:
Enter the number of elements: 4
Enter the elements: 20 10 40 30
Sorted array: 10 20 30 40

7.2 Quick Sort


Algorithm:
1. Partition the Array (Hoare’s Partitioning):
• Select a pivot element (typically the first element).
• Use two pointers:
– One pointer starts from the left and moves right until an element greater than or equal to the pivot is
found.
– The other pointer starts from the right and moves left until an element less than or equal to the pivot is
found.
• Swap the elements at the two pointers and continue until the pointers cross.
• Return the index where the pointers crossed.
2. Recursive Quick Sort:
• Apply the partitioning scheme to divide the array into two parts.
• Recursively sort the left and right parts.
Time Complexity:
• Best Case: O(n log n): When the pivot divides the array into two nearly equal parts.
• Worst Case: O(n2 ): When the pivot always picks the largest or smallest element.
• Average Case: O(n log n): On average, the partitioning is balanced.
Space Complexity:
• O(log n): Recursive stack space.
Code:
# include < iostream >
# include < vector >
using namespace std ;

int hoarePa rtition ( vector < int >& arr , int low , int high ) {
int pivot = arr [ low ];
int i = low - 1;
int j = high + 1;

while ( true ) {
do {
i ++;
} while ( arr [ i ] < pivot ) ;

do {
j - -;

43
} while ( arr [ j ] > pivot ) ;

if ( i >= j ) {
return j ;
}
swap ( arr [ i ] , arr [ j ]) ;
}
}

void quickSort ( vector < int >& arr , int low , int high ) {
if ( low < high ) {
int p = hoar ePartit ion ( arr , low , high ) ;
quickSort ( arr , low , p ) ;
quickSort ( arr , p + 1 , high ) ;
}
}

int main () {
int n ;
cout << " Enter the number of elements : " ;
cin >> n ;

vector < int > arr ( n ) ;


cout << " Enter the elements : " ;
for ( int i = 0; i < n ; i ++)
cin >> arr [ i ];

quickSort ( arr , 0 , n - 1) ;

cout << " Sorted array : " ;


for ( int num : arr )
cout << num << " " ;
cout << endl ;

return 0;
}

Output 1:

Enter the number of elements: 6


Enter the elements: 10 7 8 9 1 5
Sorted array: 1 5 7 8 9 10
Output 2:

Enter the number of elements: 5


Enter the elements: 50 20 40 30 10
Sorted array: 10 20 30 40 50

7.3 Merge Sort


Algorithm:
1. Divide: Recursively split the array into two halves until each subarray has only one element.
2. Conquer: Merge the two sorted halves by comparing elements and placing them in sorted order.

3. Combine: Continue merging until the entire array is sorted.


Time Complexity:
• Best Case: O(n log n): Recursion splits the array into halves (log n) and merges them (O(n)).
• Worst Case: O(n log n): Same as the best case due to consistent splitting and merging.

• Average Case: O(n log n): Same as above.


Space Complexity:
• O(n): Additional space for temporary arrays during merging.

44
Code:
# include < iostream >
# include < vector >
using namespace std ;

void merge ( vector < int >& arr , int left , int mid , int right ) {
int n1 = mid - left + 1;
int n2 = right - mid ;

vector < int > leftArr ( n1 ) , rightArr ( n2 ) ;

for ( int i = 0; i < n1 ; i ++)


leftArr [ i ] = arr [ left + i ];
for ( int i = 0; i < n2 ; i ++)
rightArr [ i ] = arr [ mid + 1 + i ];

int i = 0 , j = 0 , k = left ;
while ( i < n1 && j < n2 )
{
if ( leftArr [ i ] <= rightArr [ j ])
arr [ k ++] = leftArr [ i ++];
else
arr [ k ++] = rightArr [ j ++];
}

while ( i < n1 )
arr [ k ++] = leftArr [ i ++];

while ( j < n2 )
arr [ k ++] = rightArr [ j ++];
}

void mergeSort ( vector < int >& arr , int left , int right ) {
if ( left < right ) {
int mid = left + ( right - left ) / 2;

mergeSort ( arr , left , mid ) ;


mergeSort ( arr , mid + 1 , right ) ;
merge ( arr , left , mid , right ) ;
}
}

int main () {
int n ;
cout << " Enter the number of elements : " ;
cin >> n ;

vector < int > arr ( n ) ;


cout << " Enter the elements : " ;
for ( int i = 0; i < n ; i ++)
cin >> arr [ i ];

mergeSort ( arr , 0 , n - 1) ;

cout << " Sorted array : " ;


for ( int num : arr )
cout << num << " " ;

cout << endl ;

return 0;
}

Output 1:
Enter the number of elements: 5
Enter the elements: 12 11 13 5 6
Sorted array: 5 6 11 12 13
Output 2:
Enter the number of elements: 6
Enter the elements: 38 27 43 3 9 82

45
Sorted array: 3 9 27 38 43 82

8 Recursion
8.1 Fibonacci Sequence using recursion
Algorithm:
1. Define a recursive function fibonacci(n):
• Base cases:
– If n = 0, return 0.
– If n = 1, return 1.
• Recursive case: Return the sum of fibonacci(n - 1) and fibonacci(n - 2).
2. In the main function:
• Take the number of terms (n) as input.
• Print the Fibonacci sequence by calling the fibonacci function iteratively for indices 0 to n − 1.
Time Complexity:
• O(2n ): Each call splits into two further calls, resulting in exponential growth of computations.
Space Complexity:
• O(n): Due to recursive function call stack.
Code:
# include < iostream >
using namespace std ;

int fibonacci ( int n )


{
if ( n == 0)
return 0;
if ( n == 1)
return 1;
return fibonacci ( n - 1) + fibonacci ( n - 2) ;
}

int main ()
{
int n ;
cout << " Enter the number of terms : " ;
cin >> n ;

if ( n <= 0)
{
cout << " Number of terms must be positive . " << endl ;
return 0;
}

cout << " Fibonacci Sequence : " ;


for ( int i = 0; i < n ; i ++)
cout << fibonacci ( i ) << " " ;
cout << endl ;

return 0;
}

Output 1:
Enter the number of terms: 5
Fibonacci Sequence: 0 1 1 2 3
Output 2:
Enter the number of terms: 8
Fibonacci Sequence: 0 1 1 2 3 5 8 13

46
8.2 Fibonacci Sequence using Memo Table
Algorithm:

1. Create a memo table (array) to store Fibonacci numbers, initialized with -1.
2. Define a recursive function fibonacci(n):
• Base cases:
– If n = 0, return 0.
– If n = 1, return 1.
• If the Fibonacci number for n is already computed (i.e., memo[n] != -1), return memo[n].
• Otherwise, compute fibonacci(n - 1) + fibonacci(n - 2), store it in memo[n], and return the result.
3. In the main function:
• Take the number of terms (n) as input.
• Print the Fibonacci sequence by calling the fibonacci function iteratively for indices 0 to n − 1.

Time Complexity:
• O(n): Each Fibonacci number is computed only once and stored in the memo table.
Space Complexity:

• O(n): For the memo table and the recursion stack.


Code:
# include < iostream >
# include < vector >
using namespace std ;

int fibonacci ( int n , vector < int > & memo )


{
if ( n == 0)
return 0;
if ( n == 1)
return 1;

if ( memo [ n ] != -1)
return memo [ n ];

memo [ n ] = fibonacci ( n - 1 , memo ) + fibonacci ( n - 2 , memo ) ;


return memo [ n ];
}

int main ()
{
int n ;
cout << " Enter the number of terms : " ;
cin >> n ;

if ( n <= 0)
{
cout << " Number of terms must be positive . " << endl ;
return 0;
}

vector < int > memo (n , -1) ;

cout << " Fibonacci Sequence : " ;


for ( int i = 0; i < n ; i ++)
cout << fibonacci (i , memo ) << " " ;
cout << endl ;

return 0;
}

Output 1:

47
Enter the number of terms: 5
Fibonacci Sequence: 0 1 1 2 3

Output 2:
Enter the number of terms: 8
Fibonacci Sequence: 0 1 1 2 3 5 8 13

8.3 Tower of Hanoi


Algorithm:
1. Define a recursive function towerOfHanoi(n, source, destination, auxiliary):
• Base Case: If n = 1, move the disk from the source rod to the destination rod.
• Recursive Case:
– Move n − 1 disks from the source rod to the auxiliary rod, using the destination rod as a helper.
– Move the nth disk from the source rod to the destination rod.
– Move n − 1 disks from the auxiliary rod to the destination rod, using the source rod as a helper.
2. In the main function:

• Take the number of disks (n) as input.


• Call the recursive function to display the steps.
Time Complexity:
• O(2n − 1): Each recursive call splits into two smaller recursive calls, doubling the work with each additional disk.

Space Complexity:
• O(n): Due to the recursive call stack.
Code:
# include < iostream >
using namespace std ;

void towerOfHanoi ( int n , char source , char destination , char auxiliary )


{
if ( n == 1)
{
cout << " Move disk 1 from " << source << " to " << destination << endl ;
return ;
}
towerOfHanoi ( n - 1 , source , auxiliary , destination ) ;
cout << " Move disk " << n << " from " << source << " to " << destination << endl ;
towerOfHanoi ( n - 1 , auxiliary , destination , source ) ;
}

int main ()
{
int n ;
cout << " Enter the number of disks : " ;
cin >> n ;

if ( n <= 0)
{
cout << " Number of disks must be positive . " << endl ;
return 0;
}

cout << " The sequence of moves to solve Tower of Hanoi is :\ n " ;
towerOfHanoi (n , ’A ’ , ’C ’ , ’B ’) ;
return 0;
}

Output 1:

48
Enter the number of disks: 2
The sequence of moves to solve Tower of Hanoi is:
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
Output 2:
Enter the number of disks: 3
The sequence of moves to solve Tower of Hanoi is:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

49

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