Sorting problems
This is a process of re-arranging elements in such a way that numbers are in ascending or descending order .
This process can be performed using various Techniques .some of them are
1)Bubble sort
2)insertion sort
3)merge sort
4)Quick sort
5)Merge sort
6)heap sort e.t.c
Basic of all sorting techniques is BUBBLE SORT
Explanation: In this process we swap the numbers. that is we change position of numbers , such that they are in expected order
Code
int a[5]={1,4,2,5,3,};
for(int i=0;i<5;i++)
{
for(int j=0;j<5-i-1;j++)
{
if(a[j]>a[j+1])// If this condition is reversed it becomes descending order
{
int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
This method sorts the array given in ascending order and output will be a sorted array .
TRACING
I | J | elements | swapping | array after each swap |
0 | 4 | 1,4,2,5,3 | swap(a[1],a[2])
swap(a[3],a[4])
| 1,2,4,5,3
1,2,4,3,5 |
1 | 3 | 2,4,3 | swap(4,3) | 1,2,3,4,5 |
2 | 2 | 4 | no swap | 1,2,3,4,5 |
3 | 1 | 3 | no swap | 1,2,3,4,5 |
4 | 0 | 5 | no swap | 1,2,3,4,5 |
_________________________________________________________________________TO BE CONTINUED ............
_________________________________________________________________________Thank you .
__________________________________________________________________________ Happy learning.