0% found this document useful (0 votes)
6 views

Unit-4 C programming

The document provides an overview of various searching and sorting algorithms, including Linear Search, Binary Search, Selection Sort, Bubble Sort, and Insertion Sort, detailing their algorithms, advantages, disadvantages, and time complexities. It also includes algorithms for finding the square root of a number using binary search, reversing an array, and reversing a string. Each algorithm is explained with step-by-step procedures and example code in C.

Uploaded by

ranbirkashyap29
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)
6 views

Unit-4 C programming

The document provides an overview of various searching and sorting algorithms, including Linear Search, Binary Search, Selection Sort, Bubble Sort, and Insertion Sort, detailing their algorithms, advantages, disadvantages, and time complexities. It also includes algorithms for finding the square root of a number using binary search, reversing an array, and reversing a string. Each algorithm is explained with step-by-step procedures and example code in C.

Uploaded by

ranbirkashyap29
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/ 13

Linear Search

Linear Search (also called sequential search) is a simple searching technique where we
check each element one by one in a list or array until we find the desired value (called the
key) or reach the end of the list.

Step-by-Step Algorithm for Linear Search

Let:

 arr be the array of n elements,

 key be the element to search.

📘 Algorithm Steps

1. Start

2. Input the array arr[] of size n and the value to search, key.

3. Set index i = 0.

4. Repeat steps 5 to 6 until i < n:

5. If arr[i] == key, then

Print "Element found at index i"


Stop
6. Else, set i = i + 1

7.If end of array is reached and key is not found, then


Print "Element not found"

8End

Example :

Array = [10, 20, 30, 40], Key = 30

 Compare 10 → not equal

 Compare 20 → not equal

 Compare 30 → match found at index 2 → Stop

Linear Search is a basic method to find an element (called the key) in a list or array. You start
from the first element and check each one, one by one. If the current element matches the
key, you stop and return its position. If not, you move to the next element and keep checking
until you reach the end of the array. If you go through the whole array and don't find the key,
then it means the element is not present. It’s easy to use and works well for small lists, but it
can be slow for large ones because it checks each item individually.

Advantages:

1. Easy to understand and implement.

2. No need for sorting the array beforehand.

3. Works well for small datasets.

Disadvantages:

1. Slow for large arrays – checks every element one by one.

2. Inefficient compared to other searching methods like binary search.

3. High time complexity – takes O(n) time in worst case.

time complexity of Linear Search

 Best Case: O(1)

 Average Case: O(n)

 Worst Case: O(n)

Binary Search

Binary Search is a searching algorithm used to find the position of a target value within a
sorted list. It works by repeatedly dividing the search range in half.

Advantages of Binary Search

1. Fast and efficient for searching in large sorted arrays.

2. Time complexity is O(log n) – very quick compared to linear search.

3. Requires fewer comparisons than other search methods.


4. Easy to implement using recursion or iteration.

Disadvantages of Binary Search

1. Works only on sorted data, not on unsorted arrays.

2. Requires extra steps to sort if data is not sorted.

3. Not suitable for linked lists (due to lack of random access).

4. Slightly harder to implement than linear search for beginners.

Binary Search Algorithm in C

1. Start

2. Set low = 0, high = n - 1

3. Repeat while low <= high


a. Calculate mid = (low + high) / 2
b. If arr[mid] == target
→ Return mid (element found)
c. Else if arr[mid] < target
→ Set low = mid + 1
d. Else
→ Set high = mid – 1

4. If not found, return -1 (element not in array)


5. End

Binary search is an efficient method to find a specific value in a sorted array. The algorithm
works by repeatedly dividing the search range in half. It starts by comparing the target value
to the middle element of the array. If the middle element matches the target, the search is
complete. If the target is greater than the middle value, the search continues in the right half
of the array. If the target is smaller, the search continues in the left half. This process is
repeated until the target is found or the search range becomes empty. Binary search
significantly reduces the number of comparisons needed, making it much faster than linear
search for large datasets. However, it only works if the data is sorted.

Time Complexity of Binary Search

Case Time Complexity


Best O(1)
Average O(log n)
Worst O(log n)
Sorting

Sorting means arranging elements in a specific order — either ascending (small to large) or
descending (large to small).
Sorting is useful because it makes searching, analyzing, and processing data faster and easier.

Selection Sort

Selection Sort is a simple sorting algorithm that works by repeatedly finding the smallest
(or largest) element from the unsorted part of the array and placing it at the beginning of
the sorted part. It divides the array into two parts:

 Sorted part (at the beginning)

 Unsorted part (the rest of the array)

In each step, it selects the minimum from the unsorted part and swaps it with the first
element of that part.

Selection Sort Algorithm in C

1. Start

2. Repeat for i = 0 to n - 2

a. Set min = i

b. Repeat for j = i + 1 to n - 1

If arr[j] < arr[min], then set min = j

c. Swap arr[i] and arr[min]

3. End

Selection sort works by repeatedly finding the smallest element from the unsorted part of
the array and placing it at the correct position in the sorted part. The algorithm starts at the
beginning of the array and assumes the first element is the minimum. It then checks the rest
of the array to find if there is any smaller element. If a smaller element is found, it updates
the minimum index. After scanning the entire unsorted part, it swaps the minimum element
found with the current position. This process is repeated for every position in the array
except the last one, as it will automatically be in the correct place by then. The sorted part of
the array grows one element at a time from the beginning, while the unsorted part keeps
shrinking. Even if the array is already sorted, selection sort performs the same number of
comparisons, making it less efficient for large datasets.
Time Complexity of Selection Sort

Case Time Complexity

Best O(n²)

Average O(n²)

Worst O(n²)

Advantages of Selection Sort

1. Simple to understand and implement.

2. Does not require extra space, works in-place.

3. Useful when memory is limited.

Disadvantages of Selection Sort

1. Inefficient for large arrays due to many comparisons and swaps.

2. Always takes the same time even if the array is already sorted.

3. Slower than algorithms like Merge Sort, Quick Sort, or even Insertion Sort.

Bubble Sort

Bubble Sort is a simple comparison-based sorting algorithm that repeatedly compares and
swaps adjacent elements if they are in the wrong order. This process continues until the
entire array is sorted.

It’s called "bubble" sort because larger elements gradually "bubble up" to the end of the
list in each pass.

Algorithm
1. Start

2. Repeat for i = 0 to n - 2

a. Repeat for j = 0 to n - i - 2

If arr[j] > arr[j + 1], then swap arr[j] and arr[j + 1]

4. End

Bubble Sort works by repeatedly comparing each pair of adjacent elements in the array and
swapping them if they are in the wrong order (i.e., the left element is greater than the
right). After the first full pass, the largest element reaches the end of the array. In the next
pass, the second-largest element moves to its correct position, and so on. This continues
until no more swaps are needed, meaning the array is sorted. With each pass, the number of
elements to be checked decreases because the largest elements have already been placed at
the end. While it is easy to implement and understand, bubble sort is inefficient for large
datasets due to the high number of comparisons and swaps, especially if the array is initially
in reverse order.

Advantages of Bubble Sort

1. Very simple to write and understand.

2. No extra memory needed (in-place sorting).

3. Useful for teaching purposes and small datasets.

Disadvantages of Bubble Sort

1. Very slow for large lists due to many unnecessary comparisons and swaps.

2. Time complexity remains high even if the array is nearly sorted.

3. Less efficient than algorithms like Merge Sort, Quick Sort, or Insertion Sort.

Time Complexity of Bubble Sort

Case Time Complexity

Best O(n)

Average O(n²)

Worst O(n²)
Insertion Sort

Insertion Sort is a simple sorting algorithm that builds the final sorted array one element at
a time by picking elements and inserting them into their correct position in the sorted part
of the array.

Algorithm

1. Start

2. Repeat for i = 1 to n - 1

a. Set key = arr[i]

b. Set j = i - 1

c. While j >= 0 and arr[j] > key

- Move arr[j] to arr[j + 1]

- Decrement j by 1

d. Insert key at arr[j + 1]

3. End

Insertion Sort works like sorting playing cards in your hand. You start with one card
(element) and pick the next one. Then, you compare it with the cards already sorted (to its
left) and insert it in the right position by shifting larger elements one step to the right. This
process continues until all elements are placed in their correct positions. The left side of the
array is always sorted, and the algorithm keeps inserting the next element into this sorted
part. It works very efficiently for small or nearly sorted arrays, making only a few shifts in
such cases.

Advantages of Insertion Sort

1. Very simple and intuitive algorithm.

2. Efficient for small or nearly sorted arrays.

3. In-place sorting — doesn’t require extra memory.

4. Stable sort — maintains the order of equal elements.


Disadvantages of Insertion Sort

1. Slow for large datasets — performance drops with increasing size.

2. Not suitable for large unsorted arrays.

3. Has high time complexity in the worst case.

Time Complexity of Insertion Sort

Case Time Complexity

Best O(n)

Average O(n²)

Worst O(n²)

Algorithm in C to Find Square Root (Using Binary Search Method)

1. Start

2. Input a number `n`

3. Set `low = 0`, `high = n`, and define a precision value (e.g., 0.0001)

4. Repeat while (high - low > precision)

a. Set mid = (low + high) / 2

b. If (mid * mid == n), return mid

c. If (mid * mid < n), set low = mid

d. Else, set high = mid

5. Return mid as the square root (approximate)

6. End
This algorithm uses binary search to find the square root of a number n. It starts with a
range from 0 to n (because the square root must lie in this range). In each step, it calculates
the midpoint and squares it.

 If mid² == n, we've found the exact square root.

 If mid² < n, then the actual square root lies to the right, so we move the low to mid.

 If mid² > n, then the square root lies to the left, so we move the high to mid.
This process continues until the difference between low and high is very small

Program

#include <stdio.h>

int findSquareRoot(int n) {

int low = 0, high = n, mid, result = -1;

while (low <= high) {

mid = (low + high) / 2;

if (mid * mid == n)

return mid;

else if (mid * mid < n) {

result = mid; // store the floor value

low = mid + 1;

} else {

high = mid - 1;

return result; // return the integer part of square root

int main() {
int number;

printf("Enter a number: ");

scanf("%d", &number);

if (number < 0) {

printf("Square root of a negative number is not real.\n");

} else {

int result = findSquareRoot(number);

printf("Integer square root of %d is %d\n", number, result);

return 0;

Array Reversal

Reversing an array means reordering its elements in the opposite direction, i.e., the first
becomes last, the second becomes second last, and so on.

Algorithm

1. Start

2. Input array size `n` and array elements `arr[]`

3. Set two pointers: `start = 0`, `end = n - 1`

4. Repeat while `start < end`

a. Swap arr[start] and arr[end]

b. Increment start by 1

c. Decrement end by 1

5. End

We use two pointers, one starting from the beginning and one from the end of the array.
We swap the values at these positions and then move the pointers inward (start++, end--).
This continues until the pointers meet or cross. The array is now reversed in-place, meaning
no extra array is needed.

Program

#include <stdio.h>

void reverseArray(int arr[], int n) {

int start = 0, end = n - 1, temp;

while (start < end) {

// Swap arr[start] and arr[end]

temp = arr[start];

arr[start] = arr[end];

arr[end] = temp;

// Move pointers

start++;

end--;

int main() {

int n, i;

printf("Enter the size of the array: ");

scanf("%d", &n);

int arr[n];

printf("Enter %d elements: ", n);

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

scanf("%d", &arr[i]);

reverseArray(arr, n);

printf("Reversed array: ");


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

printf("%d ", arr[i]);

return 0;

String Reversal

To reverse a string, we rearrange its characters so that the last character becomes the first,
the second last becomes the second, and so on.

Algorithm

1. Start

2. Input a string `str`

3. Set two pointers: `start = 0`, `end = length of string - 1`

4. Repeat while `start < end`

a. Swap str[start] and str[end]

b. Increment start by 1

c. Decrement end by 1

5. End

We use two pointers — one from the beginning of the string and one from the end. We
swap the characters at these positions. Then we move the start pointer forward and the end
pointer backward. This continues until both pointers meet or cross. This way, the string gets
reversed in-place (without using extra memory).

#include <stdio.h>

#include <string.h>

void reverseString(char str[]) {

int start = 0;

int end = strlen(str) - 1;

char temp;
while (start < end) {

// Swap characters

temp = str[start];

str[start] = str[end];

str[end] = temp;

// Move pointers

start++;

end--;

int main() {

char str[100];

printf("Enter a string: ");

gets(str);

reverseString(str);

printf("Reversed string: %s\n", str);

return 0;

You might also like