Sunteți pe pagina 1din 12

Assignment:

Date:
Description:
Linear search, also known as sequential search, is a process that checks every element in the
list sequentially until the desired element is found. The computational complexity for linear
search is O (n), making it generally much less efficient than binary search (O (log n)). But
when list items can be arranged in order from greatest to least and the probabilities appear as
geometric distribution (f (x) = (1-p) x-1p, x=1, 2), then linear search can have the potential to
be notably faster than binary search.
Algorithm:
Linear Search (Array A, Value x)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit

Program:
/*linear search in c*/
#include <stdio.h>
using namespace std;
int main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search)
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}

Output:
When the above c program is compile and executed, it will produce the following result

Time Complexity Analysis:

Best case:
In the best possible case,
 The element being searched may be found at the first position.
 In this case, the search terminates in success with just one comparison.
 Thus in best case, linear search algorithm takes O(1) operations.

Worst Case:
In the worst possible case,
 The element being searched may be present at the last position or not present in the array at
all.
 In the former case, the search terminates in success with n comparisons.
 In the latter case, the search terminates in failure with n comparisons.
 Thus in worst case, linear search algorithm takes O(n) operations.
Time Complexity of Linear Search Algorithm is O(n).
Assignment:
Date:
Description:
A binary search, also known as a half-interval search, is an algorithm used in computer
science to locate a specified value (key) within an array. For the search to be binary, the array
must be sorted in either ascending or descending order.

Algorithm:

1) Start with the middle element:


2) If the target value is equal to the middle element of the array, then return the
index of the middle element.
3) If not, then compare the middle element with the target value,
4) If the target value is greater than the number in the middle index, then pick
the elements to the right of the middle index, and start with Step 1.
5) If the target value is less than the number in the middle index, then pick the
elements to the left of the middle index, and start with Step 1.
6) When a match is found, return the index of the element matched.
7) If no match is found, then return -1

function binary_search(A, n, T):


L := 0
R := n − 1
while L <= R:
m := floor((L + R) / 2)
if A[m] < T:
L := m + 1
else if A[m] > T:
R := m - 1
else:
return m
return unsuccessful
Program:
/*Binary search in c*/
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");


scanf("%d",&n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)


scanf("%d",&array[c]);

printf("Enter value to find\n");


scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last) {


if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);

return 0;
}
Output:
When the above c program is compile and executed, it will produce the following result

Time Complexity analysis:


When we say the time complexity is log n, we actually mean log2 n, although the base of the
log doesn't matter in asymptotic notations, but still to understand this better, we generally
consider a base of 2.
Let's first understand what log2(n) means.
Expression: log2 (n)
---------------
For n = 2:
log2 (21) = 1
Output = 1
---------------
For n = 4
log2 (22) = 2
Output = 2Now that we know how log2(n) works with different values of n, it will be easier
for us to relate it with the time complexity of the binary search algorithm and also to
understand how we can find out the number of steps required to search any number using
binary search for any value of n.
Assignment:
Date:
Description: Selection sort is basically a selection of an element position from the
start with the other rest of the elements. Elements are compared and exchanged depending on
the condition and then selection position is shifted to the next position till it reaches to the
end.

Algorithm: Step 1 − Set MIN to location 0


Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted
procedure selection sort
list : array of items
n : size of list

for i = 1 to n - 1
min = i

for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for
if indexMin != i then
swap list[min] and list[i]
end if
end for

Program:
/*Selection sort in c*/
#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;
for (i = 0; i < n-1; i++)
{
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
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;
}
Output:
When the above c program is compile and executed, it will produce the following result

Time Complexity analysis:


O(n2) as there are two nested loops.
Assignment:
Date:
Description: This is an in-place comparison-based sorting algorithm. Here, a sub-list is
maintained which is always sorted. For example, the lower part of an array is maintained to
be sorted. An element which is to be 'insert'ed in this sorted sub-list, has to find its
appropriate place and then it has to be inserted there. Hence the name, insertion sort.
Algorithm: Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
Value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted
1. insertionSort(array)
2. mark first element as sorted
3. for each unsorted element X
4. 'extract' the element X
5. for j <- lastSortedIndex down to 0
6. if current element j > X
7. move sorted element to the right by 1
8. break loop and insert X here
9. end insertionSor
Program:
/*Insertion sort in c*/

#include <stdio.h>
void printArray(int array[], int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", array[i]);
}
printf("\n");
}
void insertionSort(int array[], int size)
{
for (int step = 1; step < size; step++)
{
int key = array[step];
int j = step - 1;
while (key < array[j] && j >= 0)
{
// For descending order, change key<array[j] to key>array[j].
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}
int main()
{
int data[] = {9, 5, 1, 4, 3};
int size = sizeof(data) / sizeof(data[0]);
insertionSort(data, size);
printf("Sorted array in ascending order:\n");
printArray(data, size);
}
Output:
When the above c program is compile and executed, it will produce the following result

Time Complexity analysis:


 Worst Case Complexity: O(n2)

Suppose, an array is in ascending order, and you want to sort it in descending order. In this
case, worse case complexity occers.
Each element has to be compared with each of the other elements so, for every nth
element, (n-1) number of comparisons are made.
Thus, the total number of comparisons = n*(n-1) ~ n2

 Best Case Complexity: O(n)


When the array is already sorted, the outer loop runs for n number of times whereas the inner
loop does not run at all. So, there is only n number of comparison. Thus, complexity is linear.

 Average Case Complexity: O(n2)


It occurs when the elements of a array are in jumbled order (neither ascending nor
descending).
Assignment:
Date:
Description: Merge sort is a divide-and-conquer algorithm based on the idea of
breaking down a list into several sub-lists until each sublist consists of a single element and
merging those sub lists in a manner that results into a sorted list.
Algorithm:
MergeSort(A, p, r)
If p > r
return;
q = (p+r)/2;
mergeSort(A, p, q)
mergeSort(A, q+1, r)
merge(A, p, q, r)
Program:
/*Merge sort in c*/
#include<stdio.h>
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);

int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}

void mergesort(int a[],int i,int j)


{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid);
mergesort(a,mid+1,j);
merge(a,i,mid,mid+1,j);
}
}

void merge(int a[],int i1,int j1,int i2,int j2)


{
int temp[50];
int i,j,k;
i=i1;
j=i2;
k=0;

while(i<=j1 && j<=j2)


{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}

while(i<=j1)
temp[k++]=a[i++];
while(j<=j2)
temp[k++]=a[j++];
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}
Output:
When the above c program is compile and executed, it will produce the following result

Complexity Analysis of Merge Sort:


Merge Sort is quite fast, and has a time complexity of O(n*log n). It is also a stable
sort, which means the "equal" elements are ordered in the same order in the sorted
list.
In this section we will understand why the running time for merge sort is O(n*log n).
As we have already learned in Binary Search that whenever we divide a number into
half in every stpe, it can be represented using a logarithmic function, which is log
n and the number of steps can be represented by log n + 1(at most)
Also, we perform a single step operation to find out the middle of any subarray,
i.e. O(1).
And to merge the subarrays, made by dividing the original array of n elements, a
running time of O(n) will be required.
Hence the total time for mergeSort function will become n(log n + 1), which gives
us a time complexity of O(n*log n).
Worst Case Time Complexity [ Big-O ]: O(n*log n)
Best Case Time Complexity [Big-omega]: O(n*log n)
Average Time Complexity [Big-theta]: O(n*log n)

S-ar putea să vă placă și