Unit 4-1
Unit 4-1
Bubble sort is a simple and intuitive sorting algorithm. It repeatedly swaps adjacent
elements if they are in the wrong order until the array is sorted. In this algorithm, the
largest element "bubbles up" to the end of the array in each iteration. Bubble sort is
inefficient for large data sets, but it is useful for educational purposes and small data
sets. In this article, we will implement the bubble sort algorithm in C programming
language.
Bubble sort works on the repeatedly swapping of adjacent elements until they are not in
the intended order. It is called bubble sort because the movement of array elements is
just like the movement of air bubbles in the water. Bubbles in water rise up to the
surface; similarly, the array elements in bubble sort move to the end in each iteration.
Algorithm
In the algorithm given below, suppose arr is an array of n elements. The
assumed swap function in the algorithm will swap the values of given array elements.
1. begin BubbleSort(arr)
2. for all array elements
3. if arr[i] > arr[i+1]
4. swap(arr[i], arr[i+1])
5. end if
6. end for
7. return arr
8. end BubbleSort
To understand the working of bubble 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).
First Pass
Sorting will start from the initial two elements. Let compare them to check which is
greater.
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 -
Now, compare 32 and 35.
Here, 35 is greater than 32. So, there is no swapping required as they are already sorted.
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 -
Second Pass
The same process will be followed for second iteration.
Here, 10 is smaller than 32. So, swapping is required. After swapping, the array will be -
Now, move to the third iteration.
Third Pass
The same process will be followed for third iteration.
Here, 10 is smaller than 26. So, swapping is required. After swapping, the array will be -
Fourth pass
Similarly, after the fourth iteration, the array will be -
1. Time Complexity
Case Time Complexity
o Best Case Complexity - It occurs when there is no sorting required, i.e. the array
is already sorted. The best-case time complexity of bubble sort is O(n).
o Average Case Complexity - It occurs when the array elements are in jumbled
order that is not properly ascending and not properly descending. The average
case time complexity of bubble sort is O(n2).
o Worst Case Complexity - It occurs when the array elements are required to be
sorted in reverse order. That means suppose you have to sort the array elements
in ascending order, but its elements are in descending order. The worst-case time
complexity of bubble sort is O(n2).
2. Space Complexity
Stable YES
o The space complexity of bubble sort is O(1). It is because, in bubble sort, an extra
variable is required for swapping.
o The space complexity of optimized bubble sort is O(2). It is because two extra
variables are required in optimized bubble sort.
This method will reduce the execution time and also optimizes the bubble sort.
1. bubbleSort(array)
2. n = length(array)
3. repeat
4. swapped = false
5. for i = 1 to n - 1
6. if array[i - 1] > array[i], then
7. swap(array[i - 1], array[i])
8. swapped = true
9. end if
10. end for
11. n=n-1
12. until not swapped
13. end bubbleSort
1. #include<stdio.h>
2. void print(int a[], int n) //function to print array elements
3. {
4. int i;
5. for(i = 0; i < n; i++)
6. {
7. printf("%d ",a[i]);
8. }
9. }
10. void bubble(int a[], int n) // function to implement bubble sort
11. {
12. int i, j, temp;
13. for(i = 0; i < n; i++)
14. {
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. }
26. void main ()
27. {
28. int i, j,temp;
29. int a[5] = { 10, 35, 32, 13, 26};
30. int n = sizeof(a)/sizeof(a[0]);
31. printf("Before sorting array elements are - \n");
32. print(a, n);
33. bubble(a, n);
34. printf("\nAfter sorting array elements are - \n");
35. print(a, n);
36. }
Output
Selection Sort Algorithm
In this article, we will discuss the Selection sort Algorithm. The working procedure of selection
sort is also simple. This article will be very helpful and interesting to students as they might face
selection sort as a question in their examinations. So, it is important to discuss the topic.
In selection sort, the smallest value among the unsorted elements of the array is selected in every
pass and inserted to its appropriate position into the array. It is also the simplest algorithm. It is
an in-place comparison sorting algorithm. In this algorithm, the array is divided into two parts,
first is sorted part, and another one is the unsorted part. Initially, the sorted part of the array is
empty, and unsorted part is the given array. Sorted part is placed at the left, while the unsorted
part is placed at the right.
In selection sort, the first smallest element is selected from the unsorted array and placed at the
first position. After that second smallest element is selected and placed in the second position.
The process continues until the array is entirely sorted.
The average and worst-case complexity of selection sort is O(n2), where n is the number of
items. Due to this, it is not suitable for large data sets.
Algorithm
1. SELECTION SORT(arr, n)
2.
3. Step 1: Repeat Steps 2 and 3 for i = 0 to n-1
4. Step 2: CALL SMALLEST(arr, i, n, pos)
5. Step 3: SWAP arr[i] with arr[pos]
6. [END OF LOOP]
7. Step 4: EXIT
8.
9. SMALLEST (arr, i, n, pos)
10. Step 1: [INITIALIZE] SET SMALL = arr[i]
11. Step 2: [INITIALIZE] SET pos = i
12. Step 3: Repeat for j = i+1 to n
13. if (SMALL > arr[j])
14. SET SMALL = arr[j]
15. SET pos = j
16. [END OF if]
17. [END OF LOOP]
18. Step 4: RETURN pos
To understand the working of the Selection sort algorithm, let's take an unsorted array. It will be
easier to understand the Selection sort via an example.
Now, for the first position in the sorted array, the entire array is to be scanned sequentially.
At present, 12 is stored at the first position, after searching the entire array, it is found that 8 is
the smallest value.
So, swap 12 with 8. After the first iteration, 8 will appear at the first position in the sorted array.
For the second position, where 29 is stored presently, we again sequentially scan the rest of the
items of unsorted array. After scanning, we find that 12 is the second lowest element in the array
that should be appeared at second position.
Now, swap 29 with 12. After the second iteration, 12 will appear at the second position in the
sorted array. So, after two iterations, the two smallest values are placed at the beginning in a
sorted way.
The same process is applied to the rest of the array elements. Now, we are showing a pictorial
representation of the entire sorting process.
1. Time Complexity
Case Time Complexity
Best Case O(n2)
Average Case O(n2)
Worst Case O(n2)
o Best Case Complexity - It occurs when there is no sorting required, i.e. the array
is already sorted. The best-case time complexity of selection sort is O(n2).
o Average Case Complexity - It occurs when the array elements are in jumbled
order that is not properly ascending and not properly descending. The average
case time complexity of selection sort is O(n2).
o Worst Case Complexity - It occurs when the array elements are required to be
sorted in reverse order. That means suppose you have to sort the array elements
in ascending order, but its elements are in descending order. The worst-case time
complexity of selection sort is O(n2).
2. Space Complexity
1. #include <stdio.h>
2.
3. void selection(int arr[], int n)
4. {
5. int i, j, small;
6.
7. for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
8. {
9. small = i; //minimum element in unsorted array
10.
11. for (j = i+1; j < n; j++)
12. if (arr[j] < arr[small])
13. small = j;
14. // Swap the minimum element with the first element
15. int temp = arr[small];
16. arr[small] = arr[i];
17. arr[i] = temp;
18. }
19. }
20.
21. void printArr(int a[], int n) /* function to print the array */
22. {
23. int i;
24. for (i = 0; i < n; i++)
25. printf("%d ", a[i]);
26. }
27.
28. int main()
29. {
30. int a[] = { 12, 31, 25, 8, 32, 17 };
31. int n = sizeof(a) / sizeof(a[0]);
32. printf("Before sorting array elements are - \n");
33. printArr(a, n);
34. selection(a, n);
35. printf("\nAfter sorting array elements are - \n");
36. printArr(a, n);
37. return 0;
38. }
Output:
Insertion sort works similar to the sorting of playing cards in hands. It is assumed that
the first card is already sorted in the card game, and then we select an unsorted card. If
the selected unsorted card is greater than the first card, it will be placed at the right
side; otherwise, it will be placed at the left side. Similarly, all unsorted cards are taken
and put in their exact place.
The same approach is applied in insertion sort. The idea behind the insertion sort is that
first take one element, iterate it through the sorted array. Although it is simple to use, it
is not appropriate for large data sets as the time complexity of insertion sort in the
average case and worst case is O(n2), where n is the number of items. Insertion sort is
less efficient than the other sorting algorithms like heap sort, quick sort, merge sort, etc.
o Simple implementation
o Efficient for small data sets
o Adaptive, i.e., it is appropriate for data sets that are already substantially sorted.
Algorithm
The simple steps of achieving the insertion sort are listed as follows -
Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then
move to the next element. Else, shift greater elements in the array towards the right.
To understand the working of the insertion sort algorithm, let's take an unsorted array. It
will be easier to understand the insertion sort via an example.
Here, 31 is greater than 12. That means both elements are already in ascending order.
So, for now, 12 is stored in a sorted sub-array.
Now, move to the next two elements and compare them.
Here, 25 is smaller than 31. So, 31 is not at correct position. Now, swap 31 with 25.
Along with swapping, insertion sort will also check it with all elements in the sorted
array.
For now, the sorted array has only one element, i.e. 12. So, 25 is greater than 12. Hence,
the sorted array remains sorted after swapping.
Now, two elements in the sorted array are 12 and 25. Move forward to the next
elements that are 31 and 8.
Now, the sorted array has three items that are 8, 12 and 25. Move to the next items that
are 31 and 32.
Hence, they are already sorted. Now, the sorted array includes 8, 12, 25 and 31.
1. Time Complexity
o Best Case Complexity - It occurs when there is no sorting required, i.e. the array
is already sorted. The best-case time complexity of insertion sort is O(n).
o Average Case Complexity - It occurs when the array elements are in jumbled
order that is not properly ascending and not properly descending. The average
case time complexity of insertion sort is O(n2).
o Worst Case Complexity - It occurs when the array elements are required to be
sorted in reverse order. That means suppose you have to sort the array elements
in ascending order, but its elements are in descending order. The worst-case time
complexity of insertion sort is O(n2).
2. Space Complexity
1. #include <stdio.h>
2.
3. void insert(int a[], int n) /* function to sort an aay with insertion sort */
4. {
5. int i, j, temp;
6. for (i = 1; i < n; i++) {
7. temp = a[i];
8. j = i - 1;
9.
10. while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one posi
tion ahead from their current position*/
11. {
12. a[j+1] = a[j];
13. j = j-1;
14. }
15. a[j+1] = temp;
16. }
17. }
18.
19. void printArr(int a[], int n) /* function to print the array */
20. {
21. int i;
22. for (i = 0; i < n; i++)
23. printf("%d ", a[i]);
24. }
25.
26. int main()
27. {
28. int a[] = { 12, 31, 25, 8, 32, 17 };
29. int n = sizeof(a) / sizeof(a[0]);
30. printf("Before sorting array elements are - \n");
31. printArr(a, n);
32. insert(a, n);
33. printf("\nAfter sorting array elements are - \n");
34. printArr(a, n);
35.
36. return 0;
37. }
Output:
Program to take a number from user and to get the square root
Let's consider an example to print the square root of a number by taking an input from
the user and then use the sqrt() function in C.
ADVERTISEMENT
1. #include <stdio.h>
2. #include <conio.h>
3. #include <math.h>
4.
5. int main ()
6. {
7. // declare an integer variable
8. int x;
9. double res;
10. printf (" Enter any number to get the square root: ");
11. scanf (" %d", &x);
12. // use the sqrt() function to return integer values
13. res = sqrt(x);
14. printf (" \n The square root of %d is: %.2lf", x, res);
15.
16. return 0;
17. }
Output:
Library function in C
Introduction:
In the world of programming, libraries are one of the most important and useful tools
available. They are prewritten pieces of code that can be used to perform specific tasks,
such as sorting or searching data, without the need to write the code from scratch. C is
a popular programming language that has a wide range of libraries available for use. In
this article, we will explore the concept of library functions in C and how they can be
used to simplify programming tasks.
1. Write the function code: Write the code for the function that performs the
required task.
2. Create a header file: Create a header file for the function that contains the
function prototype.
3. Compile the code: Compile the code into an object file using a compiler.
4. Create the library: Create a library by combining the object file with other
required object files.
5. Link the library: Link the library to the program that will use the function.
1. Saves time: Library functions provide prewritten code that can be used to
perform common programming tasks, saving programmers time and effort.
2. Increases productivity: With library functions, programmers can quickly develop
complex programs without worrying about the low-level details.
3. Improves code readability: Library functions provide a standardized way of
performing common tasks, making the code more readable and easier to
maintain.
4. Reduces bugs: The use of library functions reduces the chances of introducing
bugs into the program since the code has already been tested and debugged.
Library Functions:
In C, functions can be defined within the code of a program, but these are not
considered library functions. Library functions are pre-written functions that are
included in a library and can be used in multiple programs without the need to write the
code again.
Linking Libraries:
To use library functions in a C program, the library needs to be linked with the
program during the compilation process. It can be done in two ways: static
linking and dynamic linking.
Static Linking: In static linking, the library functions are copied into the executable file
during compilation. It means that the executable file includes all the necessary code and
can be run independently of the library.
Dynamic Linking: In dynamic linking, the library functions are not copied into the
executable file. Instead, the program references the library functions at runtime. It
means that the library file needs to be present on the system when the program is run.
Header Files:
Header files are used to declare the prototypes for the functions included in the library.
The header file contains the function declarations, as well as any
necessary macros, constants, and types. Header files are included in the source code
using the #include directive.
For example, if we wanted to use the printf() function from the standard C library, we
would include the stdio.h header file at the top of our code:
1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello, World!");
5. return 0;
6. }
In this example, we include the stdio.h header file, which declares the prototype for
the printf() function. It allows us to use the printf() function without having to write
the code ourselves.
To create a custom library function, the function needs to be defined in a source file
with a .c extension, and the function prototype needs to be declared in a header file
with a .h extension. After that, the source file is compiled into an object file with a .o
extension, and the object files for all the functions in the library are combined into a
single library file with a .a or .so extension, depending on whether static or dynamic
linking is used.
Example:
Here's an example of a custom library function that calculates the factorial of a number:
1. int factorial(int n)
2. {
3. if (n == 0) {
4. return 1;
5. } else {
6. return n * factorial(n - 1);
7. }
8. }
In this example, we define a recursive function called factorial() that calculates the
factorial of a given number. After that, we can compile this source file into an object file
using a command like:
We can then combine this object file with other object files to create a library file using a
command like:
1. arrcslibmylib.afactorial.o
It creates a static library file called libmylib.a that can be linked with other programs
using the -lmylib option during compilation.
Header Files:
Header files are used to declare the function prototypes for library functions,
both standard and custom. A function prototype is a declaration of a function's
name, return type, and parameter types, but without the function body. Header files
also include any necessary macros, constants, and types that are needed by the
functions.
For example, here's the header file for our factorial() function:
When using library functions in a program, the corresponding header files need to be
included using the #include directive.
For example:
1. #include "factorial.h"
2.
3. int main()
4. {
5. int n = 5;
6. int result = factorial(n);
7. printf("Factorial of %d is %d\n", n, result);
8. return 0;
9. }
In this example, we include the factorial.h header file, which declares the prototype for
the factorial() function. After that, we call the factorial() function with a value
of 5 and print the result using printf().
Output:
HelloWorld
In this example, we include the string.h library and use the strcat() function to
concatenate the str2 string onto the end of the str1 string. After that, we
use printf() to print the resulting concatenated string.
Example 2:
Let's take an example using the math.h library to perform mathematical calculations.
1. #include <stdio.h>
2. #include <math.h>
3.
4. int main()
5. {
6. double x = 4.0;
7.
8. // calculate the square root of x
9. double y = sqrt(x);
10.
11. // print the result
12. printf("The square root of %f is %f", x, y);
13.
14. return 0;
15. }
Output:
Explanation:
In this example, we include the math.h library and use the sqrt() function to calculate
the square root of the variable x. After that, we use printf() to print the result.
Example 3:
Let's take an example using the time.h library to work with dates and times.
1. #include <stdio.h>
2. #include <time.h>
3.
4. int main()
5. {
6. time_t t = time(NULL);
7. struct tm *tm = localtime(&t);
8.
9. // print the current date and time
10. printf("Current date and time: %s", asctime(tm));
11.
12. return 0;
13. }
Output:
In this example, we include the time.h library and use the time() function to get the
current time, which is then passed to the localtime() function to convert it to a local
time structure. After that, we use printf() and the asctime() function to print
the current date and time in a readable format.
Conclusion:
In conclusion, library functions in C are a powerful tool that can simplify programming
tasks and improve code maintainability. Standard library functions provide a wide
range of functionality that is part of the C language specification, while user-defined
library functions can be created by the programmer and added to a library for later
use. Using library functions saves time, increases productivity, improves code
readability, and reduces bugs. By utilizing library functions, programmers can focus on
solving complex problems without worrying about the low-level details.