Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Sorting Algorithms

Uploaded by

RK
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Sorting Algorithms

Uploaded by

RK
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Sorting Algorithms

int A[10] = { 5, 4, 10, 2, 30, 45, 34, 14,


Sorting is the process of arranging the 18, 9 )
elements of an array so that they can
be placed either in ascending or The Array sorted in ascending order
descending order. For example, will be given as;
consider an array A = {A1, A2, A3, A4,
?? An }, the array is called to be in A[] = { 2, 4, 5, 9, 10, 14, 18, 30, 34, 45
ascending order if element of A are }
arranged like A1 > A2 > A3 > A4 > A5
> ? > An . There are many techniques by using
which, sorting can be performed. In
Consider an array; this section of the tutorial, we will
discuss each method in detail.

Sorting Algorithms

Sorting algorithms are described in the following table along with the description.

Sorting Description
Algorithms

Bubble Sort It is the simplest sort method which performs sorting by repeatedly moving the
largest element to the highest index of the array. It comprises of comparing
each element to its adjacent element and replace them accordingly.

Bucket Sort Bucket sort is also known as bin sort. It works by distributing the element into
the array also called buckets. In this sorting algorithms, Buckets are sorted
individually by using different sorting algorithm.

Comb Sort Comb Sort is the advanced form of Bubble Sort. Bubble Sort compares all the
adjacent values while comb sort removes all the turtle values or small values
near the end of the list.

Counting It is a sorting technique based on the keys i.e. objects are collected according
Sort to keys which are small integers. Counting sort calculates the number of
occurrence of objects and stores its key values. New array is formed by adding
previous key elements and assigning to objects.

Heap Sort In the heap sort, Min heap or max heap is maintained from the array elements
deending upon the choice and the elements are sorted by deleting the root
element of the heap.

Insertion Sort As the name suggests, insertion sort inserts each element of the array to its
proper place. It is a very simple sort method which is used to arrange the deck
of cards while playing bridge.
Merge Sort Merge sort follows divide and conquer approach in which, the list is first
divided into the sets of equal elements and then each half of the list is sorted
by using merge sort. The sorted list is combined again to form an elementary
sorted array.

Quick Sort Quick sort is the most optimized sort algorithm which performs sorting in O(n
log n) comparisons. Like Merge sort, quick sort also work by using divide and
conquer approach.

Radix Sort In Radix sort, the sorting is done as we do sort the names according to their
alphabetical order. It is the linear sorting algorithm used for Integers.

Selection Selection sort finds the smallest element in the array and place it on the first
Sort place on the list, then it finds the second smallest element in the array and
place it on the second place. This process continues until all the elements are
moved to their correct ordering. It carries running time O(n2) which is worst
than insertion sort.

Shell Sort Shell sort is the generalization of insertion sort which overcomes the
drawbacks of insertion sort by comparing elements separated by a gap of
several positions.

Bubble sort Algorithm ○ simple and shortcode is


preferred
Bubble sort works on the repeatedly
swapping of adjacent elements until
they are not in the intended order. It is Algorithm
called bubble sort because the
movement of array elements is just like In the algorithm given below, suppose
the movement of air bubbles in the arr is an array of n elements. The
water. Bubbles in water rise up to the assumed swap function in the
surface; similarly, the array elements in algorithm will swap the values of given
bubble sort move to the end in each array elements.
iteration.
1. begin BubbleSort(arr)
Although it is simple to use, it is 2. for all array elements
primarily used as an educational tool 3. if arr[i] > arr[i+1]
because the performance of bubble 4. swap(arr[i], arr[i+1])
sort is poor in the real world. It is not 5. end if
suitable for large data sets. The 6. end for
average and worst-case complexity of 7. return arr
Bubble sort is O(n2), where n is a 8. end BubbleSort
number of items.
Working of Bubble sort Algorithm
Bubble short is majorly used where -
To understand the working of bubble
○ complexity does not matter sort algorithm, let's take an unsorted
array. We are taking a short and
accurate array, as we know the
complexity of bubble sort is O(n2).

Let the elements of array are -


Here, 10 is smaller than 35 that are not
sorted. So, swapping is required. Now,
we reach at the end of the array. After
first pass, the array will be -
First Pass

Sorting will start from the initial two


elements. Let compare them to check
which is greater.
Now, move to the second iteration.

Second Pass

The same process will be followed for


second iteration.
Here, 32 is greater than 13 (32 > 13),
so it is already sorted. Now, compare
32 with 26.

Here, 26 is smaller than 36. So,


swapping is required. After swapping
new array will look like -
Here, 10 is smaller than 32. So,
swapping is required. After swapping,
the array will be -

Now, compare 32 and 35.

Now, move to the third iteration.


Here, 35 is greater than 32. So, there is
no swapping required as they are Third Pass
already sorted.
The same process will be followed for
Now, the comparison will be in third iteration.
between 35 and 10.
9. }
10. void bubble(int a[], int n) //
function to implement bubble
sort
11. {
12. int i, j, temp;
Here, 10 is smaller than 26. So, 13. for(i = 0; i < n; i++)
swapping is required. After swapping, 14. {
the array will be - 15. for(j = i+1; j < n; j++)
16. {
17. if(a[j] < a[i])
18. {
19. temp = a[i];
20. a[i] = a[j];
21. a[j] = temp;
22. }
23. }
24. }
25. }
Now, move to the fourth iteration. 26. void main ()
27. {
Fourth pass 28. int i, j,temp;
29. int a[5] = { 10, 35, 32, 13, 26};
Similarly, after the fourth iteration, the 30. int n = sizeof(a)/sizeof(a[0]);
array will be - 31. printf("Before sorting array
elements are - \n");
32. print(a, n);
33. bubble(a, n);
34. printf("\nAfter sorting array
elements are - \n");
Hence, there is no swapping required, 35. print(a, n);
so the array is completely sorted. 36. }

Implementation of Bubble sort Output

Write a program to implement bubble


sort in C language.

1. #include<stdio.h>
Linear Search Algorithm
2. void print(int a[], int n)
//function to print array Searching is the process of finding
elements some particular element in the list. If
3. { the element is present in the list, then
4. int i; the process is called successful, and
5. for(i = 0; i < n; i++) the process returns the location of that
6. { element; otherwise, the search is
7. printf("%d ",a[i]); called unsuccessful.
8. }
Two popular search methods are given array, 'val' is the value to
Linear Search and Binary Search. So, search
here we will discuss the popular 2. Step 1: set pos = -1
searching technique, i.e., Linear Search 3. Step 2: set i = 1
Algorithm. 4. Step 3: repeat step 4 while i <= n
5. Step 4: if a[i] == val
Linear search is also called as 6. set pos = i
sequential search algorithm. It is the 7. print pos
simplest searching algorithm. In Linear 8. go to step 6
search, we simply traverse the list 9. [end of if]
completely and match each element of 10. set ii = i + 1
the list with the item whose location is 11. [end of loop]
to be found. If the match is found, then 12. Step 5: if pos = -1
the location of the item is returned; 13. print "value is not present in the
otherwise, the algorithm returns NULL. array "
14. [end of if]
It is widely used to search an element 15. Step 6: exit
from the unordered list, i.e., the list in
which items are not sorted. The
Working of Linear search
worst-case time complexity of linear
search is O(n). To understand the working of linear
search algorithm, let's take an
The steps used in the implementation
unsorted array. It will be easy to
of Linear Search are listed as follows -
understand the working of linear
search with an example.
○ First, we have to traverse the
array elements using a for loop. Let the elements of array are -
○ In each iteration of for loop,
compare the search element
with the current array element,
and -
○ If the element matches, Let the element to be searched is K =
then return the index of 41
the corresponding array
element. Now, start from the first element and
○ If the element does not compare K with each element of the
match, then move to the array.
next element.
○ If there is no match or the
search element is not present in
the given array, return -1.

Algorithm
The value of K, i.e., 41, is not matched
1. Linear_Search(a, n, val) // 'a' is with the first element of the array. So,
the given array, 'n' is the size of move to the next element. And follow
the same process until the respective 12. int a[] = {70, 40, 30, 11, 57, 41,
element is found. 25, 14, 52}; // given array
13. int val = 41; // value to be
searched
14. int n = sizeof(a) / sizeof(a[0]);
// size of array
15. int res = linearSearch(a, n, val);
// Store result
16. printf("The elements of the
array are - ");
17. for (int i = 0; i < n; i++)
18. printf("%d ", a[i]);
19. printf("\nElement to be
searched is - %d", val);
20. if (res == -1)
21. printf("\nElement is not
present in the array");
22. else
23. printf("\nElement is present at
%d position of array", res);
24. return 0;
25. }

Output

Now, the element to be searched is


found. So algorithm will return the
index of the element matched. C Program to find the roots of
quadratic equation
Implementation of Linear Search
Quadratic equations are the
Write a program to implement linear polynomial equation with degree 2. It
search in C language. is represented as ax2 + bx +c = 0,
where a, b and c are the coefficient
1. #include <stdio.h> variable of the equation. The universal
2. int linearSearch(int a[], int n, int rule of quadratic equation defines that
val) { the value of 'a' cannot be zero, and the
3. // Going through array value of x is used to find the roots of
sequentially the quadratic equation (a, b). A
4. for (int i = 0; i < n; i++) quadratic equation's roots are defined
5. { in three ways: real and distinct, real
6. if (a[i] == val) and equal, and real and imaginary.
7. return i+1;
8. } Nature of the roots
9. return -1; The nature of the roots depends on the
10. } Discriminant (D) where D is.
11. int main() {
1. If D > 0, the roots are real and 3. D <- sqrt (y * y - 4 * x * z).
distinct (unequal) 4. R1 <- (-y + D) / ( 2 * x).
2. If D = 0, the roots are real and 5. R2 <- (-y - D) / (2 * x).
equal. 6. Print the roots R1 and R2.
3. If D < 0, the roots are real and 7. Stop
imaginary.

Steps to find the square roots of the /* C Program to Find the Roots of the
quadratic equation Quadratic Equation */
#include<stdio.h>
● Initialize all the variables used in #include<math.h> // it is used for
the quadratic equation. math calculation
● Take inputs of all coefficient #include<conio.h>
variables x, y and z from the void main()
user. {
● And then, find the discriminant float x, y, z, det, root1, root2, real,
of the quadratic equation using img;
the formula: printf("\n Enter the value of
● Discriminant = (y * y) - (4 * x *z). coefficient x, y and z: \n ");
● Calculate the roots based on scanf("%f %f %f", &x, &y, &z);
the nature of the discriminant of // define the quadratic formula of the
the quadratic equation. nature of the root
● If discriminant > 0, then det = y * y - 4 * x * z;
● Root1 = (-y + sqrt(det)) / (2 * x) // defines the conditions for real and
● Root2 = (-y + sqrt(det)) / (2 * x) different roots of the quadratic
● Print the roots are real and equation
distinct. if (det > 0)
● Else if (discriminant = 0) then, {
● Root1 = Root2 = -y / (2 * x). root1 = (-y + sqrt(det)) / (2 * x);
● Print both roots are real and root2 = (-y + sqrt(det)) / (2 * x);
equal. printf("\n Value of root1 = %.2f and
● Else (discriminant < 0), the roots value of root2 = %.2f", root1, root2);
are distinct complex where, }
● Real part of the root is: Root1 = // elseif condition defines both roots
Root2 = -y / (2 * x) or real = -y / ( real and equal root) are equal in the
(2 * x). quadratic equation
● Imaginary part of the root is: else if (det == 0)
sqrt( -discriminant) / (2 * x). {
● Print both roots are imaginary, root1 = root2 = -y / (2 * x); // both
where first root is (r + i) img and roots are equal;
second root is (r - i) img. printf("\n Value of root1 = %.2f
● Exit or terminate the program. and Value of root2 = %.2f", root1,
root2);
Pseudo Code of the Quadratic }
Equation // if det < 0, means both roots are
1. Start real and imaginary in the quadratic
2. Input the coefficient variable, x, equation.
y and z. else {
real = -y / (2 * x);
img = sqrt(-det) / (2 * x);
printf("\n value of root1 = %.2f +
%.2fi and value of root2 = %.2f - %.2fi ",
real, img, real, img);
}
getch();
}

Output:

● %.2f means floating-point


number with 2 decimal points

You might also like