Sorting
Sorting
Sorting
Sorting Techniques
128
20. Sorting Algorithm Data Structures & Algorithms
Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way
to arrange data in a particular order. Most common orders are in numerical or
lexicographical order.
The importance of sorting lies in the fact that data searching can be optimized to a very
high level, if data is stored in a sorted manner. Sorting is also used to represent data in
more readable formats. Following are some of the examples of sorting in real-life
scenarios:
However, in some sorting algorithms, the program requires space which is more than or
equal to the elements being sorted. Sorting which uses equal or more space is called not-
in-place sorting. Merge-sort is an example of not-in-place sorting.
129
Data Structures & Algorithms
If a sorting algorithm, after sorting the contents, changes the sequence of similar content
in which they appear, it is called unstable sorting.
A non-adaptive algorithm is one which does not take into account the elements which are
already sorted. They try to force every single element to be re-ordered to confirm their
sortedness.
Important Terms
Some terms are generally coined while discussing sorting techniques, here is a brief
introduction to them −
Increasing Order
A sequence of values is said to be in increasing order, if the successive element is greater
than the previous one. For example, 1, 3, 4, 6, 8, 9 are in increasing order, as every next
element is greater than the previous element.
Decreasing Order
A sequence of values is said to be in decreasing order, if the successive element is less
than the current one. For example, 9, 8, 6, 4, 3, 1 are in decreasing order, as every next
element is less than the previous element.
130
Data Structures & Algorithms
Non-Increasing Order
A sequence of values is said to be in non-increasing order, if the successive element is
less than or equal to its previous element in the sequence. This order occurs when the
sequence contains duplicate values. For example, 9, 8, 6, 3, 3, 1 are in non-increasing
order, as every next element is less than or equal to (in case of 3) but not greater than
any previous element.
Non-Decreasing Order
A sequence of values is said to be in non-decreasing order, if the successive element is
greater than or equal to its previous element in the sequence. This order occurs when the
sequence contains duplicate values. For example, 1, 3, 3, 6, 8, 9 are in non-decreasing
order, as every next element is greater than or equal to (in case of 3) but not less than
the previous one.
131
21. Bubble Sort Algorithm Data Structures & Algorithms
Bubble sort starts with very first two elements, comparing them to check which one is
greater.
In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we
compare 33 with 27.
We find that 27 is smaller than 33 and these two values must be swapped.
132
Data Structures & Algorithms
Next we compare 33 and 35. We find that both are in already sorted positions.
We know then that 10 is smaller 35. Hence they are not sorted.
We swap these values. We find that we have reached the end of the array. After one
iteration, the array should look like this −
133
Data Structures & Algorithms
To be precise, we are now showing how an array should look like after each iteration. After
the second iteration, it should look like this −
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sorts learns that an array is completely sorted.
134
Data Structures & Algorithms
Algorithm
We assume list is an array of n elements. We further assume that swap function swaps
the values of the given array elements.
begin BubbleSort(list)
return list
end BubbleSort
Pseudocode
We observe in algorithm that Bubble Sort compares each pair of array element unless the
whole array is completely sorted in an ascending order. This may cause a few complexity
issues like what if the array needs no more swapping as all the elements are already
ascending.
To ease-out the issue, we use one flag variable swapped which will help us see if any
swap has happened or not. If no swap has occurred, i.e. the array requires no more
processing to be sorted, it will come out of the loop.
loop = list.count;
135
Data Structures & Algorithms
swapped = true
end if
end for
end for
Implementation
One more issue we did not address in our original algorithm and its improvised
pseudocode, is that, after every iteration the highest values settles down at the end of the
array. Hence, the next iteration need not include already sorted elements. For this
purpose, in our implementation, we restrict the inner loop to avoid already sorted values.
To know about bubble sort implementation in C programming language, please click here.
Implementation in C
#include <stdio.h>
#include <stdbool.h>
#define MAX 10
int list[MAX] = {1,8,4,6,0,3,5,2,7,9};
void display(){
int i;
printf("[");
136
Data Structures & Algorithms
printf("]\n");
}
void bubbleSort() {
int temp;
int i,j;
swapped = true;
printf(" => swapped [%d, %d]\n",list[j],list[j+1]);
}else {
printf(" => not swapped\n");
}
137
Data Structures & Algorithms
main(){
printf("Input Array: ");
display();
printf("\n");
bubbleSort();
printf("\nOutput Array: ");
display();
}
If we compile and run the above program, it will produce the following result −
Input Array: [1 8 4 6 0 3 5 2 7 9 ]
Items compared: [ 1, 8 ] => not swapped
Items compared: [ 8, 4 ] => swapped [4, 8]
Items compared: [ 8, 6 ] => swapped [6, 8]
Items compared: [ 8, 0 ] => swapped [0, 8]
Items compared: [ 8, 3 ] => swapped [3, 8]
Items compared: [ 8, 5 ] => swapped [5, 8]
Items compared: [ 8, 2 ] => swapped [2, 8]
Items compared: [ 8, 7 ] => swapped [7, 8]
Items compared: [ 8, 9 ] => not swapped
138
Data Structures & Algorithms
Iteration 1#: [1 4 6 0 3 5 2 7 8 9 ]
Items compared: [ 1, 4 ] => not swapped
Items compared: [ 4, 6 ] => not swapped
Items compared: [ 6, 0 ] => swapped [0, 6]
Items compared: [ 6, 3 ] => swapped [3, 6]
Items compared: [ 6, 5 ] => swapped [5, 6]
Items compared: [ 6, 2 ] => swapped [2, 6]
Items compared: [ 6, 7 ] => not swapped
Items compared: [ 7, 8 ] => not swapped
Iteration 2#: [1 4 0 3 5 2 6 7 8 9 ]
Items compared: [ 1, 4 ] => not swapped
Items compared: [ 4, 0 ] => swapped [0, 4]
Items compared: [ 4, 3 ] => swapped [3, 4]
Items compared: [ 4, 5 ] => not swapped
Items compared: [ 5, 2 ] => swapped [2, 5]
Items compared: [ 5, 6 ] => not swapped
Items compared: [ 6, 7 ] => not swapped
Iteration 3#: [1 0 3 4 2 5 6 7 8 9 ]
Items compared: [ 1, 0 ] => swapped [0, 1]
Items compared: [ 1, 3 ] => not swapped
Items compared: [ 3, 4 ] => not swapped
Items compared: [ 4, 2 ] => swapped [2, 4]
Items compared: [ 4, 5 ] => not swapped
Items compared: [ 5, 6 ] => not swapped
Iteration 4#: [0 1 3 2 4 5 6 7 8 9 ]
Items compared: [ 0, 1 ] => not swapped
Items compared: [ 1, 3 ] => not swapped
Items compared: [ 3, 2 ] => swapped [2, 3]
Items compared: [ 3, 4 ] => not swapped
Items compared: [ 4, 5 ] => not swapped
Iteration 5#: [0 1 2 3 4 5 6 7 8 9 ]
Items compared: [ 0, 1 ] => not swapped
Items compared: [ 1, 2 ] => not swapped
Items compared: [ 2, 3 ] => not swapped
Items compared: [ 3, 4 ] => not swapped
Output Array: [0 1 2 3 4 5 6 7 8 9 ]
139
22. Insertion Sort Data Structures & Algorithms
The array is searched sequentially and unsorted items are moved and inserted into the
sorted sub-list (in the same array). This algorithm is not suitable for large data sets as its
average and worst case complexity are of Ο(n2), where n is the number of items.
It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-
list.
140
Data Structures & Algorithms
It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see
that the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the
sorted sub-list remains sorted after swapping.
By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.
So we swap them.
141
Data Structures & Algorithms
We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items.
This process goes on until all the unsorted values are covered in a sorted sub-list. Now we
shall see some programming aspects of insertion sort.
Algorithm
Now we have a bigger picture of how this sorting technique works, so we can derive simple
steps by which we can achieve insertion sort.
Pseudocode
procedure insertionSort( A : array of items )
int holePosition
int valueToInsert
142
Data Structures & Algorithms
end for
end procedure
Implementation in C
#include <stdio.h>
#include <stdbool.h>
#define MAX 7
143
Data Structures & Algorithms
printf("=\n");
}
void display(){
int i;
printf("[");
printf("]\n");
}
void insertionSort(){
int valueToInsert;
int holePosition;
int i;
144
Data Structures & Algorithms
if(holePosition != i){
printf(" item inserted : %d, at position : %d\n" ,
valueToInsert,holePosition);
// insert the number at hole position
intArray[holePosition] = valueToInsert;
}
printf("Iteration %d#:",i);
display();
}
}
main(){
printf("Input Array: ");
display();
printline(50);
insertionSort();
printf("Output Array: ");
display();
printline(50);
}
If we compile and run the above program, it will produce the following result −
145
Data Structures & Algorithms
item moved :3
item moved :2
item inserted :1, at position :0
iteration 4#: [1, 2, 3, 4, 6, 9, 7]
iteration 5#: [1, 2, 3, 4, 6, 9, 7]
item moved :9
item moved :6
item inserted :7, at position :4
iteration 6#: [1, 2, 3, 4, 7, 6, 9]
Output Array: [1, 2, 3, 4, 7, 6, 9]
==================================================
146
23. Selection Sort Data Structures & Algorithms
The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. This process continues
moving unsorted array boundary by one element to the right.
This algorithm is not suitable for large data sets as its average and worst case complexities
are of O(n2), where n is the number of items.
For the first position in the sorted list, the whole list is scanned sequentially. The first
position where 14 is stored presently, we search the whole list and find that 10 is the
lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the minimum value
in the list, appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in a
linear manner.
We find that 14 is the second lowest value in the list and it should appear at the second
place. We swap these values.
147
Data Structures & Algorithms
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.
148
Data Structures & Algorithms
Algorithm
Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted
Pseudocode
procedure selection sort
list : array of items
n : size of list
for i = 1 to n - 1
/* set current element as minimum*/
min = i
for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for
end for
end procedure
149
Data Structures & Algorithms
Implementation in C
#include <stdio.h>
#include <stdbool.h>
#define MAX 7
printf("=\n");
}
void display(){
int i;
printf("[");
150
Data Structures & Algorithms
printf("]\n");
}
void selectionSort(){
int indexMin,i,j;
if(indexMin != i){
printf("Items swapped: [ %d, %d ]\n" , intArray[i],
intArray[indexMin]);
printf("Iteration %d#:",(i+1));
display();
}
}
151
Data Structures & Algorithms
main(){
printf("Input Array: ");
display();
printline(50);
selectionSort();
printf("Output Array: ");
display();
printline(50);
}
If we compile and run the above program, it will produce the following result −
152
24. Merge Sort Algorithm Data Structures & Algorithms
Merge sort is a sorting technique based on divide and conquer technique. With worst-case
time complexity being Ο(n log n), it is one of the most respected algorithms.
Merge sort first divides the array into equal halves and then combines them in a sorted
manner.
We know that merge sort first divides the whole array iteratively into equal halves unless
the atomic values are achieved. We see here that an array of 8 items is divided into two
arrays of size 4.
This does not change the sequence of appearance of items in the original. Now we divide
these two arrays into halves.
We further divide these arrays and we achieve atomic value which can no more be divided.
Now, we combine them in exactly the same manner as they were broken down. Please
note the color codes given to these lists.
We first compare the element for each list and then combine them into another list in a
sorted manner. We see that 14 and 33 are in sorted positions. We compare 27 and 10 and
in the target list of 2 values we put 10 first, followed by 27. We change the order of 19
and 35 whereas 42 and 44 are placed sequentially.
153
Data Structures & Algorithms
In the next iteration of the combining phase, we compare lists of two data values, and
merge them into a list of found data values placing all in a sorted order.
After the final merging, the list should look like this −
Algorithm
Merge sort keeps on dividing the list into equal halves until it can no more be divided. By
definition, if it is only one element in the list, it is sorted. Then, merge sort combines the
smaller sorted lists keeping the new list sorted too.
Pseudocode
We shall now see the pseudocodes for merge sort functions. As our algorithms point out
two main functions − divide & merge.
Merge sort works with recursion and we shall see our implementation in the same way.
154
Data Structures & Algorithms
l2 = mergesort( l2 )
var c as array
return c
end procedure
To know about merge sort implementation in C programming language, please click here.
155
Data Structures & Algorithms
Implementation in C
We shall see the implementation of merge sort in C programming language here −
#include <stdio.h>
#define max 10
int a[10] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44 };
int b[10];
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}
156
Data Structures & Algorithms
int main() {
int i;
sort(0, max);
If we compile and run the above program, it will produce the following result −
157
25. Shell Sort Data Structures & Algorithms
Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm.
This algorithm avoids large shifts as in case of insertion sort, if the smaller value is to the
far right and has to be moved to the far left.
This algorithm uses insertion sort on a widely spread elements, first to sort them and then
sorts the less widely spaced elements. This spacing is termed as interval. This interval is
calculated based on Knuth's formula as −
h = h * 3 + 1
where −
h is interval with initial value 1
This algorithm is quite efficient for medium-sized data sets as its average and worst case
complexity are of O(n), where n is the number of items.
158
Data Structures & Algorithms
We compare values in each sub-list and swap them (if necessary) in the original array.
After this step, the new array should look like this −
Then, we take interval of 2 and this gap generates two sub-lists - {14, 27, 35, 42}, {19,
10, 33, 44}
We compare and swap the values, if required, in the original array. After this step, the
array should look like this −
Finally, we sort the rest of the array using interval of value 1. Shell sort uses insertion sort
to sort the array.
159
Data Structures & Algorithms
160
Data Structures & Algorithms
We see that it required only four swaps to sort the rest of the array.
Algorithm
Following is the algorithm for shell sort.
Pseudocode
Following is the pseudocode for shell sort.
procedure shellSort()
A : array of items
/* calculate interval*/
while interval < A.length /3 do:
interval = interval * 3 + 1
end while
161
Data Structures & Algorithms
end for
/* calculate interval*/
interval = (interval -1) /3;
end while
end procedure
To know about shell sort implementation in C programming language, please click here.
Implementation in C
#include <stdio.h>
#include <stdbool.h>
#define MAX 7
printf("=\n");
}
162
Data Structures & Algorithms
void display(){
int i;
printf("[");
printf("]\n");
}
void shellSort(){
int inner, outer;
int valueToInsert;
int interval = 1;
int elements = MAX;
int i = 0;
while(interval > 0) {
printf("iteration %d#:",i);
display();
163
Data Structures & Algorithms
intArray[inner] = valueToInsert;
printf(" item inserted :%d, at position :%d\n",valueToInsert,inner);
}
int main() {
printf("Input Array: ");
display();
printline(50);
shellSort();
printf("Output Array: ");
display();
printline(50);
return 1;
}
If we compile and run the above program, it will produce the following result −
164
Data Structures & Algorithms
165
26. Quick Sort Data Structures & Algorithms
Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of
data into smaller arrays. A large array is partitioned into two arrays one of which holds
values smaller than the specified value, say pivot, based on which the partition is made
and another array holds values greater than the pivot value.
Quick sort partitions an array and then calls itself recursively twice to sort the two resulting
subarrays. This algorithm is quite efficient for large-sized data sets as its average and
worst case complexity are of O(nlogn), where n is the number of items.
The pivot value divides the list into two parts. And recursively, we find the pivot for each
sub-lists until all lists contains only one element.
166
Data Structures & Algorithms
while True do
while A[++leftPointer] < pivot do
//do-nothing
end while
end while
swap leftPointer,right
return leftPointer
end function
167
Data Structures & Algorithms
if right-left <= 0
return
else
pivot = A[right]
partition = partitionFunc(left, right, pivot)
quickSort(left,partition-1)
quickSort(partition+1,right)
end if
end procedure
To know about quick sort implementation in C programming language, please click here.
Implementation in C
#include <stdio.h>
#include <stdbool.h>
#define MAX 7
printf("=\n");
168
Data Structures & Algorithms
void display(){
int i;
printf("[");
printf("]\n");
}
while(true){
169
Data Structures & Algorithms
intArray[leftPointer],intArray[rightPointer]);
swap(leftPointer,rightPointer);
}
main(){
printf("Input Array: ");
display();
printline(50);
quickSort(0,MAX-1);
printf("Output Array: ");
display();
printline(50);
}
If we compile and run the above program, it will produce the following result −
170
Data Structures & Algorithms
Input Array: [4 6 3 2 1 9 7 ]
==================================================
pivot swapped :9,7
Updated Array: [4 6 3 2 1 7 9 ]
pivot swapped :4,1
Updated Array: [1 6 3 2 4 7 9 ]
item swapped :6,2
pivot swapped :6,4
Updated Array: [1 2 3 4 6 7 9 ]
pivot swapped :3,3
Updated Array: [1 2 3 4 6 7 9 ]
Output Array: [1 2 3 4 6 7 9 ]
==================================================
171
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: