0% found this document useful (0 votes)
21 views10 pages

Portfolio Chapter 4

Uploaded by

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

Portfolio Chapter 4

Uploaded by

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

selection sort-

Lets consider the following array as an example: arr[] = {64, 25, 12, 22, 11}
1. For the first position in the sorted array, the whole array is traversed from
index 0 to 4 sequentially. The first position where 64 is stored presently, after
traversing whole array it is clear that 11 is the lowest value.
Thus, replace 64 with 11. After one iteration 11, which happens to be the least
value in the array, tends to appear in the first position of the sorted list.
{11,25,12,22,64}
2. For the second position, where 25 is present, again traverse the rest of the
array in a sequential manner.
After traversing, we found that 12 is the second lowest value in the array and it
should appear at the second place in the array, thus swap these values.
{11,12,25,22,64}
3.Now, for third place, where 25 is present again traverse the rest of the array
and find the third least value present in the array.
While traversing, 22 came out to be the third least value and it should appear at
the third place in the array, thus swap 22 with element present at third position.
{11,12,22,25,64}
4. Similarly, for fourth position traverse the rest of the array and find the
fourth least element in the array
As 25 is the 4th lowest value hence, it will place at the fourth position
{11,12,22,25,64}
5. At last the largest value present in the array automatically get placed at the
last position in the array
The resulted array is the sorted array
sorted => {11,12,22,25,64}
total passes: n

// C program for implementation of selection sort


#include <stdio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of unsorted subarray


for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element


if(min_idx != i)
swap(&arr[min_idx], &arr[i]);
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

Time Complexity: The time complexity of Selection Sort is O(N^2) as there are two
nested loops:

One loop to select an element of Array one by one = O(N)


Another loop to compare that element with every other Array element = O(N)
Therefore overall complexity = O(N) * O(N) = O(N*N) = O(N^2)

/
***********************************************************************************
********************************************************************/

bubble sort-
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in the wrong order. This algorithm is not suitable
for large data sets as its average and worst-case time complexity is quite high.
total passes: n-1

In Bubble Sort algorithm,


traverse from left and compare adjacent elements and the higher one is placed at
right side.
In this way, the largest element is moved to the rightmost end at first.
This process is then continued to find the second largest and place it and so on
until the data is sorted.

// Optimized implementation of Bubble sort


#include <stdbool.h>
#include <stdio.h>

void swap(int* xp, int* yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

// An optimized version of Bubble Sort


void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n - 1; i++) {
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
swapped = true;
}
}

// If no two elements were swapped by inner loop,


// then break
if (swapped == false)
break;
}
}

// Function to print an array


void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
}

// Driver program to test above functions


int main()
{
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

Time Complexity: O(N^2)

/
***********************************************************************************
********************************************************************/

insertion sort-
you pick an element from the unsorted group and put it in the right place in the
sorted group.

To achieve insertion sort, follow these steps:

1. We have to start with second element of the array as first element in the array
is assumed to be sorted.
2. Compare second element with the first element and check if the second element is
smaller then swap them.
3. Move to the third element and compare it with the second element, then the first
element and swap as necessary to put it in the correct position among the first
three elements.
4. Continue this process, comparing each element with the ones before it and
swapping as needed to place it in the correct position among the sorted elements.
5. Repeat until the entire array is sorted.
total passes n

Consider an array having elements: {23, 1, 10, 5, 2}


First Pass:
Current element is 23
The first element in the array is assumed to be sorted.
The sorted part until 0th index is : [23]
Second Pass:
Compare 1 with 23 (current element with the sorted part).
Since 1 is smaller, insert 1 before 23.
The sorted part until 1st index is: {1, 23}
Third Pass:
Compare 10 with 1 and 23 (current element with the sorted part).
Since 10 is greater than 1 and smaller than 23, insert 10 between 1 and 23.
The sorted part until 2nd index is: {1, 10, 23}
Fourth Pass:
Compare 5 with 1, 10, and 23 (current element with the sorted part).
Since 5 is greater than 1 and smaller than 10, insert 5 between 1 and 10.
The sorted part until 3rd index is: {1, 5, 10, 23}
Fifth Pass:
Compare 2 with 1, 5, 10, and 23 (current element with the sorted part).
Since 2 is greater than 1 and smaller than 5 insert 2 between 1 and 5.
The sorted part until 4th index is: {1, 2, 5, 10, 23}
Final Array:
The sorted array is: {1, 2, 5, 10, 23}
// C program for insertion sort
#include <math.h>
#include <stdio.h>

/* Function to sort an array using insertion sort*/


void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

/* Move elements of arr[0..i-1], that are


greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

// A utility function to print an array of size n


void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}

/* Driver program to test insertion sort */


int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);

return 0;
}

Time Complexity: O(N^2)


Best case: O(n), If the list is already sorted, where n is the number of elements
in the list.
Average case: O(n^2), If the list is randomly ordered
Worst case: O(n^2), If the list is in reverse order

/
***********************************************************************************
*************************************************************/

quick sort-
QuickSort is one of the best sorting algorithms developed by Tony Hoare in 1960 to
sort the array. It follows the divide-and-conquer rule like Merge Sort but unlike
Merge Sort, this algorithm does not use any extra space for sorting (though it uses
an auxiliary stack space).

The basic idea behind QuickSort is to select a “pivot” element from the array and
partition the other elements into two sub-arrays according to whether they are less
than or greater than the pivot.

Pick an element: Randomly choose any element from the pile. Call this element
“pivot.”
Divide the Pile: Separate the remaining elements into two piles – one pile having
elements that are smaller than the pivot and another with elements larger than the
pivot.
Sort the Piles: Now, repeat the same process of dividing each of the two piles
until each pile only has one element left.
Combine Sorted Piles: When all the sub piles are sorted, put them together in order
such that the smallest is on the left and the largest on the right.

8 7 6 1 0 9 2
p2 pivot
if array[0] > pivot then place p2 in array[0]
8 7 6 1 0 9 2
p2 p3 pivot
if p3 > pivot then p3++
if p3 < pivot then value(p2) <-> value(p3) , p2++, p3++
8 7 6 1 0 9 2
p2 p3 pivot

8 7 6 1 0 9 2
p2 p3 pivot

1 7 6 8 0 9 2
p2 p3 pivot

1 0 6 8 7 9 2
p2 p3 pivot
once p3 reaches just before pivot i.e p3 = pivot-1, value(p2)<->value(pivot)

1 0 2 8 7 9 6
divide from pivot

1 0 | 2 | 8 7 9 6

/
***********************************************************************************
*************************************************************/

merge sort-
Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides the input
array into two halves, calls itself for the two halves, and then it merges the two
sorted halves.

Declare left variable to 0 and right variable to n-1


• Find mid by medium formula. mid = (left+right)/2
• Call merge sort on (left,mid)
• Call merge sort on (mid+1,rear)
• Continue till left is less than right i.e stop when left = right
• Then call merge function to perform merge sort.

At first, check if the left index of array is less than the right index, if yes
then calculate its mid point
{38,27,43,3,9,82,10}
Now, as we already know that merge sort first divides the whole array iteratively
into equal halves, unless the atomic values are achieved.
Here, we see that an array of 7 items is divided into two arrays of size 4 and 3
respectively.
{38,27,43,3} {9,82,10}
Now, again find that is left index is less than the right index for both arrays, if
found yes, then again calculate mid points for both the arrays.
{38,27} {43,3} {9,82} {10}
Now, further divide these two arrays into further halves, until the atomic units of
the array is reached and further division is not possible.
{38} {27} {43} {3} {9} {82} {10}
After dividing the array into smallest units, start merging the elements again
based on comparison of size of elements
Firstly, compare the element for each list and then combine them into another list
in a sorted manner.
{27,38} {3,43} {9,82} {10}
After the final merging, the list looks like this:
{3,27,38,43} {9,10,82}
{3,9,10,27,38,43,82}

Time Complexity: O(nlog(n))

// C program for Merge Sort


#include <stdio.h>
#include <stdlib.h>

// Merges two subarrays of arr[].


// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

// Create temp arrays


int L[n1], R[n2];

// Copy data to temp arrays


// L[] and R[]
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

// Merge the temp arrays back


// into arr[l..r]
// Initial index of first subarray
i = 0;

// Initial index of second subarray


j = 0;

// Initial index of merged subarray


k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy the remaining elements


// of L[], if there are any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of


// R[], if there are any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

// l is for left index and r is


// right index of the sub-array
// of arr to be sorted
void mergeSort(int arr[], int l, int r)
{
if (l < r) {
// Same as (l+r)/2, but avoids
// overflow for large l and r
int m = l + (r - l) / 2;

// Sort first and second halves


mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

merge(arr, l, m, r);
}
}

// UTILITY FUNCTIONS
// Function to print an array
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}

// Driver code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Given array is \n");


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size);
return 0;
}

/
***********************************************************************************
*******************************************************************/

linear vs binary search-


Important Differences

Linear Search
Binary Search

In linear search input data need not to be in sorted. In binary


search input data need to be in sorted order.
It is also called sequential search. It is also called
half-interval search.
The time complexity of linear search O(n). The time
complexity of binary search O(log n).
Multidimensional array can be used. Only single
dimensional array is used.
Linear search performs equality comparisons Binary
search performs ordering comparisons
It is less complex. It is more
complex.
It is very slow process. It is very
fast process.

Linear search
Assume that item is in an array in random order and we have to find an item. Then
the only way to search for a target item is, to begin with, the first position and
compare it to the target. If the item is at the same, we will return the position
of the current item. Otherwise, we will move to the next position. If we arrive at
the last position of an array and still can not find the target, we return -1. This
is called the Linear search or Sequential search.

// Linear Search in C
#include <stdio.h>

int linearSearch(int arr[], int n, int x) {


for (int i = 0; i < n; i++) {
if (arr[i] == x) {
return i; // Element found at index i
}
}
return -1; // Element not found
}

int main() {
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;

int result = linearSearch(arr, n, x);

if (result == -1) {
printf("Element is not present in array\n");
} else {
printf("Element is present at index %d\n", result);
}

return 0;
}

BINARY SEARCH
In a binary search, however, cut down your search to half as soon as you find the
middle of a sorted list. The middle element is looked at to check if it is greater
than or less than the value to be searched. Accordingly, a search is done to either
half of the given list.

example-
0 1 2 3 4 5 6 7 8
10 12 24 29 39 40 51 56 69
to search k=29, beg=0, end=8
mid = (beg+end)/2 = 0+8/2 = 4
array[mid] = 39
array[mid]>k (i.e 29)
therefore, end = mid-1 = 3
beg remains same = 0
mid = (beg+end)/2 = 0+3/2 = 1(approx.)

array[mid] = 12
array[mid]<k (i.e 29)
therefore, beg = mid+1 = 2
end remains same = 3
mid = (beg+end)/2 = 5/2 = 2(approx.)
array[mid] = 24
array[mid]<k (i.e 29)
therefore, beg = mid+1 = 3
end remains same = 3
mid = (beg+end)/2 = 6/2 = 3

array[mid] = k
therefore, ans = mid = 3 (third element)

/* code the demonstrate the same */


#include <stdio.h>

int binary_search(int array[], int k, int beg, int end) {


if (beg > end) {
return -1; // Element not found
}

if (array[mid] == k) {
return mid; // Element found at middle index
} else if (array[mid] > k) {
return binary_search(array, k, beg, mid - 1); // Search left sub-array
} else {
return binary_search(array, k, mid + 1, end); // Search right sub-array
}
}

int main() {
int array[] = {2, 5, 8, 12, 16};
int n = sizeof(array) / sizeof(array[0]);
int k = 12;

int ans = binary_search(array, k, 0, n - 1);

if (ans == -1) {
printf("Element not found\n");
} else {
printf("Element found at index %d\n", ans);
}

return 0;
}

/
***********************************************************************************
****************************************************************/

You might also like