Sorting and Searchnig
Sorting and Searchnig
Sorting and Searchnig
LINEAR SEARCH
Assume that item is in an array in random order and we have to find an item. Then the only
way to search for a target item is, to begin with, the first position and compare it to the target.
If the item is at the same, we will return the position of the current item. Otherwise, we will
move to the next position. If we arrive at the last position of an array and still can not find the
target, we return -1. This is called the Linear search or Sequential search.
// Linear Search in C
#include <stdio.h>
BINARY SEARCH
In a binary search, however, cut down your search to half as soon as you find the middle of a
sorted list. The middle element is looked at to check if it is greater than or less than the value
to be searched. Accordingly, a search is done to either half of the given list
Below is the code syntax for the binary search.
#include <stdio.h>
1
while (low <= high) {
int mid = low + (high - low) / 2;
if (array[mid] == x)
return mid;
if (array[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
2
SORTING:
Sorting means arranging a set of data in some order. There are different methods that
are used to sort the data in ascending or descending order. These methods can be divided into
two types internal sorting and external sorting.
The internal sorting is a sorting in which the resides in the main memory of the
computer. For many applications it is not possible to store the entire data on the main
memory for two reasons, amount of main memory available is smaller than amount of data.
Secondly the main memory is a volatile device and thus will lose the data when the power is
shut down. To overcome these problems the data is stored on the secondary storage devices.
The technique which is used to sort the data which resides on the secondary devices are
called external sorting.
Internal sorting:
Sorting is an important activity and every time we insert or delete the data we need to sort the
remaining data. Therefore it should be carried out efficiently. Various algorithms are
developed for sorting such as
1. Bubble sort
2. Selection sort
3. Insertion sort
4. Merge sort
5. Shell sort
6. Heap sort
Bubble sort
This is the simplest kind of sorting method in this method. We do this bubble sort procedure
in several iterations, which are called passes.
Algorithm:
1. Read the total number of elements says n
2. Store the elements in the array
3. Set i=0
4. Compare the adjacent elements
5. Repeat the step 4 for all n elements.
6. Increment the value of I by 1 and repeat step 4,5 for I<n
3
7. Print the sorted list of elements.
8. Stop
For example
‘C’ Program
/*Bubble sort. */
#include <stdio.h>
#include <conio.h>
void main( )
{
int n,a[20];
int i, j, temp ;
clrscr( );
printf("enter the limit");
scanf("%d",&n);
printf("enter the array values:");
for(i=0;i<n;i++)
4
{
scanf("%d",&a[i]);
}
printf ( "Bubble sort.\n" ) ;
printf ( "\nArray before sorting:\n") ;
getch( ) ;
}
Selection sort:
5
selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting
the smallest (or largest) element from the unsorted portion of the list and moving it to the
sorted portion of the list.
The algorithm repeatedly selects the smallest (or largest) element from the unsorted portion
of the list and swaps it with the first element of the unsorted part. This process is repeated for
the remaining unsorted portion until the entire list is sorted.
6
// Selection sort in C
#include <stdio.h>
7
}
printf("\n");
}
// driver code
int main() {
int data[] = {20, 12, 10, 15, 2};
int size = sizeof(data) / sizeof(data[0]);
selectionSort(data, size);
printf("Sorted array in Acsending Order:\n");
printArray(data, size);
}
Insertion sort:
Insertion sort is a simple sorting algorithm that works similarly to the way you sort playing
cards in your hands. The array is virtually split into a sorted and an unsorted part. Values
from the unsorted part are picked and placed in the correct position in the sorted part.
8
/* C Program to sort an array in ascending order using Insertion Sort */
#include <stdio.h>
int main(void)
{
int n, i, j, temp;
int arr[64];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1; i < n; i++)
9
{
j = i;
while (j > 0 && arr[j - 1] > arr[j])
{
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i < n; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
Shell sort:
This method is improvement over the simple insertion sort. In this method the elements at
fixed distance are compared. The distance will then be decremented by some fixed amount
and again the comparison will be made. Finally, individual elements will be compared. Let
us take some example.
Example:
0 1 2 3 4 5 6 7
x
25 57 48 37 12 92 86 33
10
(x[2], x[7])
(x[3])
(x[4])
i.e. first iteration
0 1 2 3 4 5 6 7
x 25 57 48 37 12 92 86 33
0 1 2 3 4 5 6 7
25 57 33 37 12 92 86 48
Step 2: initially K was 5. take some d and decrement k by d. let us take d=2
k= k-d i.e. k=5-2= 3
so now compare
(x[0],x[3],x[6])
(x[1],x[4],x[7])
(x[2], x[5])
Second iteration
0 1 2 3 4 5 6 7
25 57 48 37 12 92 86 33
11
After second iteration
0 1 2 3 4 5 6 7
25 12 33 37 48 92 86 57
x
0 1 2 3 4 5 6 7
12 25 33 37 48 57 86 92
12
// C implementation of Shell Sort
#include <stdio.h>
int main()
{
int i,n,gap,arr[10],temp,j;
printf("\nenter the number of elements");
scanf("%d",&n);
printf("\nenter the array values");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("\n array before sorting");
for(i=0;i<n;i++)
printf("\t%d",arr[i]);
//shell sort begins here
for (gap=n/2;gap>0;gap=gap/2)
{
for (i=gap;i<n;i++)
{
temp = arr[i];
for (j = i;j>=gap&&arr[j - gap]>temp; j=j-gap)
arr[j] = arr[j - gap];
arr[j] = temp;
}
}
printf("\n after sorting");
for (i=0; i<n; i++)
printf("\t%d",arr[i]);
return 0;
}
13
Heap sort
Heap sort is a method in which a binary tree is used. In this method first the heap is created
using binary tree and then heap is sorted using prority queue.
Example for heap sort
Transform into max heap: After that, the task is to construct a tree from that unsorted array
and try to convert it into max heap.
To transform a heap into a max-heap, the parent node should always be greater than or equal
to the child nodes
Here, in this example, as the parent node 4 is smaller than the child node 10, thus, swap them
to build a max-heap.
Now, 4 as a parent is smaller than the child 5, thus swap both of these again and the resulted
heap and array should be like this:
14
Perform heap sort: Remove the maximum element in each step (i.e., move it to the end
position and remove that) and then consider the remaining elements and transform it into a
max heap.
Delete the root element (10) from the max heap. In order to delete this node, try to swap it
with the last node, i.e. (1). After removing the root element, again heapify it to convert it into
max heap.
Resulted heap and array should look like this:
Repeat the above steps and it will look like the following:
15
Now remove the root (i.e. 3) again and perform heapify.
Now when the root is removed once again it is sorted. and the sorted array will be like arr[] =
{1, 3, 4, 5, 10}.
16
// Heap Sort in C
#include <stdio.h>
// Function to swap the the position of two elements
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
17
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// Heap sort
for (int i = n - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
// Print an array
void printArray(int arr[], int n) {
for (int i = 0; i < n; ++i)
printf("%d ", arr[i]);
printf("\n");
}
// Driver code
int main() {
int arr[] = {1, 12, 9, 5, 6, 10};
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
Merge Sort:
18
In this sorting method, we divide the main list into two sub-lists, then go on dividing those
sub-list till we get sufficient length of that sub-list. Then we compare and sort the elements of
each list. Merge the two sub-list and sort the merged the list. This process will be repeated
until we get only one sorted list.
For example
// Merge sort in C
#include <stdio.h>
19
for (int j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];
20
arr[k] = M[j];
j++;
k++;
}
}
// Divide the array into two subarrays, sort them and merge them
void mergeSort(int arr[], int l, int r) {
if (l < r) {
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
// Driver program
int main() {
int arr[] = {6, 5, 12, 10, 9, 1};
21
int size = sizeof(arr) / sizeof(arr[0]);
22