PROGRAMMING FOR PROBLEM SOLVING(C)
SUBJECT CODE-BTPH101-23
SORTING AND THEIR DIFFERENT METHODS
Sorting:- Sorting means arranging the elements in an array so that they are placed in
ascending or descending order. For example, an unsorted array a[5] = {3, 10, 11, 2, 1} becomes
sorted in ascending order as a[5] = {1, 2, 3, 10, 11}.
METHODS:-
Bubble
Selection
Insertion
Sorting Techniques
Bubble Sort
Bubble sort is a very simple method that sorts array elements by repeatedly moving the
largest element to the highest index position of the array segment. In bubble sort,
consecutive adjacent elements in the array are compared with each other. If the element at
the lower index is greater than the element at the higher index, the two elements are
swapped.
PROGRAM:-
#include <stdio.h>
int main() {
int a[5] = {5, 2, 15, 22, 1};
int i, j, temp;
for (i = 4; i > 0; i--) {
for (j = 0; j <= i - 1; j++) {
if (a[j] > a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
, }
}
}
printf("The sorted array is = ");
for (i = 0; i < 5; i++) {
printf("%d\n", a[i]);
}
return 0;
}
OUTPUT: 1 2 5 15 22
Bubble Sort Algorithm Steps:
1. Start
2. Bubble sort (a, N) where N is the size of the array
3. Repeat step 2 for i = 4 to i >= 0
4. Repeat for j = 0 to i-1
5. If (a[j] > a[j+1]), swap a[j] and a[j+1]
6. Exit
Selection Sort
The following table is an example:
10, 4, 6, 3, 2
0, 1, 2, 3, 4 (index position)
For i = 0 (i <= 4 or i < 5)
min = a[0] = 10
To travel elements: j = i + 1, j <= 4
If a[j] < a[min]
For j = 1: a[1] < a[0] => 4 < 10 (True). min = a[1]