DSU NOTES( CH2)
DSU NOTES( CH2)
Sorting:
Bubble Sort:
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Complexity:
Best Case O(n)
Average Case O(n^2)
Worst Case O(n^2)
Advantages
➢ The bubble sort requires very little memory other than that which the array or
list itself occupies.
➢ The bubble sort consists of relatively few lines of code.
➢ With a best-case running time of O(n), the bubble sort is good for testing whether
or not a list is sorted or not.
➢ The same applies for data sets that have only a few items that need to be
swapped a few times.
Disadvantages
➢ The main disadvantage of the bubble sort method is the time it requires.
➢ With a running time of O (n^2), it is highly inefficient for large data sets.
Program to implement Bubble Sort:
#include <stdio.h>
void main()
{
int array[10], n, i, j, temp;
printf("Enter number of
elements\n"); scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
for (i = 0 ; i < ( n - 1 ); i++)
{
for (j = i+1 ; j < n; j++)
{
if (array[i] > array[j]) /* For decreasing order use < */
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
getch();
}
Selection Sort:
➢ After two iterations, two least values are positioned at the beginning in a sorted
manner.
➢ The same process is applied to the rest of the items in the array.
Fig: Selection Sort
Quick Sort:
Radix Sort:
348 348
14 14
614 614
5381 5381
47 47
After Pass 1: 5381, 14, 614,47, 348
Pass 2:
number 0 1 2 3 4 5 6 7 8 9
5381 5381
14 14
614 614
47 47
348 348
After Pass2: 14, 614, 47, 348, 5381
Pass 3:
number 0 1 2 3 4 5 6 7 8 9
14 14
614 614
+47 47
348 348
5381 5381
After pass 3: 14,47, 348, 5381,614
Pass 4:
number 0 1 2 3 4 5 6 7 8 9
14 14
47 47
348 348
5381 5381
614 614
After pass 4: 14,47,348,614, 5381
Searching:
Linear Search:
Algorithm:
1) Start
2) Accept elements from user
3) Repeat for i=0 to n-1
If a[i]=element then
Element found at location i+1
Exit Else
Element not found
4) stop
Binary search:
MSBTE Questions:
1) Write a program for selection sort and arrange the given numbers in
ascending order using selection sort(16, 23, 13, 9, 7,5)
2) Explain binary search.
3) Sort the given numbers in ascending order using radix sort(348, 14,
614, 5381, 47)
4) Write a c program for binary search.
5) Explain linear search algo.
6) Wap to sort an array of 10 elements by using bubble sort.
7) Describe bubble sort with help of example. Take minimum 4 values.
8) Describe principle of selection sort with example.