Professional Documents
Culture Documents
Bubble - Merg - Sort
Bubble - Merg - Sort
Bubble - Merg - Sort
Take the 1st number 12 and compare it with the 2nd number
9. 12 is greater than 9 so swap both the numbers.
Now take the 2nd number 12 and compare it with the 3rd
number 37. 12 is not greater than 37 so leave it.
Now take the 3rd number 37 and compare it with the 4th
number 86. 37 is not greater than 86 so leave it.
Now take the 4th number 86 and compare it with the 5th
number 2. 86 is greater than 2 so swap both the numbers.
Now take the 5th number 86 and compare it with the 6th
number 17. 86 is greater than 17 so swap both the numbers.
Now take the 6th number 86 and compare it with the 7th
number 5. 86 is greater than 5 so swap both the numbers.
#include<stdio.h>
void print(int a[], int n) //function to print array elements
{
int i;
for(i = 0; i < n; i++)
{
printf("%d ",a[i]);
}
}
void bubble(int a[], int n) // function to implement bubble sort
{
int i, j, temp;
for(i = 0; i < n; i++)
{
for(j = i+1; j < n; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
void main ()
{
int i, j,temp;
int a[5] = { 9, 7, 8, 3, 6};
int n = sizeof(a)/sizeof(a[0]);
printf("Before sorting array elements are - \n");
print(a, n);
bubble(a, n);
printf("\nAfter sorting array elements are - \n");
print(a, n);
}
Merge sort
Merge sort is similar to the quick sort algorithm as it uses the divide and
conquer approach to sort the elements. It is one of the most popular and
efficient sorting algorithm. It divides the given list into two equal halves, calls
itself for the two halves and then merges the two sorted halves.
3. Until we reach the end of either L or R, pick the larger among the elements
from L and R and place them in the correct position at A[p..q]
4. When we run out of elements in either L or R, pick up the remaining elements
and put in A[p..q]
Merge_sort(0,5)
9 7 8 3 2 1
mid=(0+5)/2=2
Merge_sort(0,2) Merge_sort(3,5)
9 7 8 3 2 1
mid=(0+2)/2=1 mid=(3+5)/2=4
9 7 8 3 2 1
mid=(0+1)/2=0 No further call mid=(3+4)/2=3 No further call
9 7 3
2
Merge(0,0,1)
7 9 2 3
Merge(3,3,4)
1 2 3
9 7 8
Merge(3,5)
Merge(0,2)
Merge_sort(0,5)
1 2 3 7 8 9
//by MK Patel Sir
// Merge sort Implementation Using C
#include <stdio.h>
int n1 = q - p + 1;
int n2 = r - q;
int i, j, k;
i = 0;
j = 0;
k = p;
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
k++;
arr[k] = L[i];
i++;
k++;
arr[k] = R[j];
j++;
k++;
// Divide the array into two subarrays, sort them and merge them
if (l < r) {
// m is the point where the array is divided into two subarrays
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
printf("\n");
int main() {
printArray(arr, size);