Professional Documents
Culture Documents
Bubble sort
Bubble Sort is a simple algorithm which is used to sort a given set of n
elements provided in form of an array with n number of elements.
Bubble Sort compares all the element one by one and sort them based
on their values
Steps 1. If the given array has to be sorted in ascending order, then
bubble sort will start by comparing the first element of the array with
the second element, if the first element is greater than the second
element, it will swap both the elements, and then move on to
compare the second and the third element, and so on.
Step 1 :Start
Step 2 : Initialize an array arr[] of size n and enter unsorted
elements
Step 3 : Set i=n-1 and j=0
Step 4 : Repeat the following steps while(i>=0)
Step 5: Set j=0
Step 6: Repeat following steps while(j<=i)
if arr[j] > arr [j+1] then
swap arr[j] with arr[j+1]
set j =j + 1
end of Step 6 while loop
set i = i – 1
End of Step 4 while loop
Step 7 : Print the Sorted array arr[i]
Step 8: End
//Bubble sort
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i, j, temp,a[20];
clrscr();
printf("Enter the no. of elements to be sorted: \n");
scanf("%d",&n);
printf("Enter the number values you want to sort\n");
for(i = 0; i < n; i++)
scanf("%d", &a[i])
for(i = 1; i < n; i++)
{
for(j=0; j<n-i; j++)
{
if(a[j] >= a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
//printing the sorted elements
printf("Array after sorting\n") ;
for ( i = 0 ; i <n ; i++ )
printf ( "%d\t", a[i] ) ;
getch();
}
Advantages
• Very simple and easy to program
• Straight forward approach
Disadvantages
• It runs slowly and hence it is not efficient. More efficient sorting
techniques are present .
• Even if the elements are sorted, n-l passes are required to sort.
Advantages of Bubble Sort over other sorting algorithms.
The space complexity for Bubble Sort is O(1), because only a single
additional memory space is required i.e. for temp variable.
Best Case Time Complexity: O(N). The best case occurs when an array is
already sorted.
Selection Sort
• Obtain the second smallest in the list and exchange it with the second
element and so on. Finally, all the items will be arranged in ascending
order.
pos = i;
for (j = i +1; j < n; j++)
{
if (a[i] < a[pos])
pos = j;
}
temp = a[pos];
a[pos] = a[i];
a[i] = temp;
Advantages
Disadvantage
Step 1 :Start
Step 2 : Initialize an array arr[] of size n and enter unsorted elements
Step 3 : Set i=0
Step 4 : Repeat the following steps while(i<n)
Step 5: Set j= i + 1
Step 6: Repeat following steps while(j<=n)
if arr[i] > arr [j] then
swap arr[i] with arr[j]
set j =j + 1
end of Step 6 while loop
set i = i + 1
End of Step 4 while loop
Step 7 : Print the Sorted array arr[i]
Step 8: End
Complexity Analysis of Selection Sort
Time Complexity: The time complexity of Selection Sort is O(N2) as
there are two nested loops:
• One loop to select an element of Array one by one = O(N)
• Another loop to compare that element with every other Array
element = O(N)
• This sorting technique works very well on large set of data. The first
step in this technique is to partition the given table into two sub-tables
such that the elements towards left of the key element (Pivot Element)
are less than the key element and elements towards right of the key
element are greater than key element.
• After this step, the array is partitioned into two sub tables. The
elements in the left sub table are lesser and elements in the right sub
table are greater than the key element
1. Selecting Pivot The process starts by selecting one element
(known as the pivot) from the list; this can be any element any
element at random, like the first or last element.
2. Rearranging the Array Now, the goal here is to rearrange the list
such that all the elements less than the pivot are towards the left of
it, and all the elements greater than the pivot are towards the right of
it.
3. The pivot element is compared to all of the items starting with the
first index. If the element is greater than the pivot element, pointer
index(pindex) is updated.
However The worst case occurs when the partition process always
picks the greatest or smallest element as the pivot so the worst case
would occur when the array is already sorted in increasing or
decreasing order.
The complexity in that case is O(n2 )
1. Best Time Complexity : O(nlogn)
2. Average Time Complexity : O(nlogn)
3. Worst Time Complexity : O(n2 )
4. Space Complexity : O(n) as we are not creating any container other
than given array therefore Space complexity will be in order of n.
Advantages Disadvantages
The quick sort is regarded as The slight disadvantage of
the best sorting algorithm. quick sort is that its worst-case
performance is similar to
average performances of the
bubble, insertion or selections
sorts.
It is able to deal well with a If the list is already sorted than
huge list of items. bubble sort is much more
efficient than quick sort
Because it sorts in place, no If the sorting element is integers
additional storage is required than radix sort is more efficient
as well than quick sort.
What is Insertion Sort?
• Insertion Sort is a sorting algorithm where the array is sorted by
taking one element at a time.
• Values from the unsorted part are picked and placed at the correct
position in the sorted part.
• Move the greater elements one position up to make space for the
swapped element.
Working of Insertion Sort algorithm
Consider an example: arr[]: {12, 11, 13, 5, 6}
12 11 13 5 6
First Pass:
Initially, the first two elements of the array are compared in insertion
sort.
12 11 13 5 6
Here, 12 is greater than 11 hence they are not in the ascending order
and 12 is not at its correct position. Thus, swap 11 and 12.
Now, two elements are present in the sorted sub-array which are 11
and 12
Both 5 and 13 are not present at their correct place so swap them
11 12 5 13 6
After swapping, elements 12 and 5 are not sorted, thus swap again
11 5 12 13 6
Now, the elements which are present in the sorted sub-array are 5, 11
and 12
Clearly, they are not sorted, thus perform swap between both
5 11 12 6 13
Line 2: Loop from i=1 till the end, to process each element.
Line 5: Compare E with the left element, if E is lesser, then move array[j]
to right by 1.
Initial array
Compare key with the first element. If the first element is greater
than key, then key is placed in front of the first element
If the first element is greater than key, then key is placed in front of
the first element.
2. Now, the first two elements are sorted.
Take the third element and compare it with the elements on the left
of it. Placed it just behind the element smaller than it. If there is no
element smaller than it, then place it at the beginning of the array.
Place 1 at the beginning
3. Similarly, place every unsorted element at its correct position.
Place 4 behind 1
Place 3 behind 1 and the array is sorted
Example
1. Time Complexity
Average Case
O(n2)
Worst Case
O(n2)
2. Space Complexity
Space Complexity
O(1)
/* Insertion Sort */
for (i = 1; i < n; i++)
{
array_key = arra[i];
j = i-1;
Divide
In the conquer step, we try to sort both the subarrays A[p..q] and A[q+1,
r]. If we haven't yet reached the base case, we again divide both these
subarrays and try to sort them.
Combine
When the conquer step reaches the base step and we get two sorted
subarrays A[p..q] and A[q+1, r] for array A[p..r], we combine the results
by creating a sorted array A[p..r] from two sorted
subarrays A[p..q] and A[q+1, r].
#include<stdio.h>
void merge(int arr[],int min,int mid,int max)
{
int tmp[30];
int i,j,k,m;
j=min;
m=mid+1;
for(i=min; j<=mid && m<=max ; i++)
{
if(arr[j]<=arr[m])
{
tmp[i]=arr[j];
j++;
}
else
{
tmp[i]=arr[m];
m++;
}
}
if(j>mid)
{
for(k=m; k<=max; k++)
{
tmp[i]=arr[k];
i++;
}
}
else
{
for(k=j; k<=mid; k++)
{
tmp[i]=arr[k];
i++;
}
}
for(k=min; k<=max; k++)
arr[k]=tmp[k];
}
void sortm(int arr[],int min,int max)
{
int mid;
if(min<max)
{
mid=(min+max)/2;
sortm(arr,min,mid);
sortm(arr,mid+1,max);
merge(arr,min,mid,max);
}
}
int main()
{
int arr[30];
int i,size;
printf("\tMerge sort\n");
printf("-----------------------------------\n");
printf(" How many numbers you want to
sort?: ");
scanf("%d",&size);
printf("\n Enter %d elements :\n ");
for(i=0; i<size; i++)
{
scanf("%d",&arr[i]);
}
sortm(arr,0,size-1);
printf("\n Sorted elements after using
merge sort:\n\n");
for(i=0; i<size; i++)
printf(" %d ",arr[i]);
return 0;
}
Our task is to merge two subarrays A[p..q] and A[q+1..r] to create
a sorted array A[p..r]. So the inputs to the function are A, p, q and
r
The merge function works as follows:
1.Create copies of the subarrays L <- A[p..q] and M <- A[q+1..r].
2.Create three pointers i, j and k
a.i maintains current index of L, starting at 1
b.j maintains current index of M, starting at 1
c.k maintains the current index of A[p..q], starting at p.
3.Until we reach the end of either L or M, pick the larger among
the elements from L and M and place them in the correct position
at A[p..q]
4.When we run out of elements in either L or M, pick up the
remaining elements and put in A[p..q]
Merge Sort Algorithm
MergeSort(arr[], l, r), where l is the index of the first element & r is
the index of the last element.
If r > l
1. Find the middle index of the array to divide it in two halves:
m = (l+r)/2
2. Call MergeSort for first half:
mergeSort(array, l, m)
3. Call mergeSort for second half:
mergeSort(array, m+1, r)
4. Recursively, merge the two halves in a sorted manner, so that only
one sorted array is left:
merge(array, l, m, r)
CASE TIME # WHEN?
COMPLEXITY COMPARISONS
Worst Case O(N logN) N logN Specific
distribution
Average Case O(N logN) NlogN Average
Best Case O(N logN) NlogN Already sorted