DS Notes Unit 02 Sorting
DS Notes Unit 02 Sorting
Sorting Techniques
Definition
Sorting refers to arranging a group of elements in ascending, descending, alphabetical or some other
ordered manner. It is an important concept used in programming which allows efficient arrangement
of list of elements inside a data structure.
The sorting operation can be performed by using various techniques. Some of those techniques are:
1. Bubble sort
2. Insertion sort
3. Selection sort
4. Quick sort
5. Merge sort
Bubble Sort
It is one of the simple algorithm and it works on the bubble strategy. At the end of each pass (outer for
loop) the largest element is moved to the right most position of the array assuming that we wish to
sort in an ascending order. The technique applied in bubble sort is to compare the adjacent elements
starting from the beginning of the array. If the element on the left is greater than the element on the
right, then these two elements are swapped, otherwise no swapping is done.
return 0;
}
#include<stdio.h>
int main()
{
int a[20], n, i, j, temp;
return 0;
}
#include<stdio.h>
int main()
{
int a[20], n, i, j, min, temp;
return 0;
}
Consider two arrays A and B in which elements are already sorted as given below:
The objective of merge sort is to merge elements of A and B into a single array C. Let i, j and k be the
variables used to keep track of elements in array A, B, and C respectively. We compare the elements in
each array and the smaller of them is added to C. If the element in array A is smaller, then i and k
variables are incremented. If the element in array B is smaller, then j and k variables are incremented.
This process is continued till either of one array get exhausted. If A gets exhausted first then the
remaining items of B are simply appended to C otherwise vice-versa. This method is also called as
simple merge or two-way merge sort.
int main()
{
int a[10], b[10], c[20], m, n, i, j, k;
i=j=k=0;
while( (i<m) && (j<n) )
{
return 0;
}
12. Now the left sub-array and right-sub array are individually sorted by calling quicksort
recursively.
int main()
{
int a[20], n, i, j, low, high;
low = 0;
high = n-1;
quicksort(a, low, high);
KLS GCC BCA Unit 2 – Sorting Techniques Page 6 | 8
Data Structures
return 0;
}
while(flag == 1)
{
while( (a[i]<pivot) && (i<j) )
i = i+1;
while(a[j]>pivot)
j = j-1;
if(i<j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
else
flag=0;
}
temp = a[low];
a[low] = a[j];
a[j] = temp;
return(j);
}
KLS GCC BCA Unit 2 – Sorting Techniques Page 7 | 8
Data Structures
Program explanation
Consider the unsorted elements: 25, 10, 72, 18, 40, 11, 32, 9
Step 1: Indices 0 1 2 3 4 5 6 7
Elements 25 10 72 18 40 11 32 9
Pivot i j
[Remember, i and j contain indices, whereas pivot contains the array element]
11 10 9 18 25 40 32 72
Pivot i j Pivot i j
Step 8: Since, i<j is false, swap pivot and a[j]. Return j and make the partition.
9 10 11 18 25 32 40 72