Unit v - Searching and Sorting
Unit v - Searching and Sorting
Algorithm
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
Pseudocode
end procedure
int main()
{
int array[100], search, c, n, position;
printf("Input number of elements in array\n");
scanf("%d", &n);
if (position == -1)
printf("%d isn't present in the array.\n", search);
else
printf("%d is present at location %d.\n", search, position+1);
return 0;
}
return -1;
}
output2
Binary Search
Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].
A simple approach is to do linear search.The time complexity of above algorithm is O(n).
Another approach to perform the same task is using Binary Search.
Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin
with an interval covering the whole array. If the value of the search key is less than the item in
the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper
half. Repeatedly check until the value is found or the interval is empty.
Example :
The idea of binary search is to use the information that the array is sorted and reduce the time
complexity to O(Log n)
intmain()
{
intarr[] = { 2, 3, 4, 10, 40 };
intn = sizeof(arr) / sizeof(arr[0]);
intx = 10;
intresult = binarySearch(arr, 0, n - 1, x);
(result == -1) ? printf("Element is not present"
" in array")
: printf("Element is present at "
"index %d",
result);
return0;
}
intmain(void)
{
intarr[] = { 2, 3, 4, 10, 40 };
intn = sizeof(arr) / sizeof(arr[0]);
intx = 10;
intresult = binarySearch(arr, 0, n - 1, x);
(result == -1) ? printf("Element is not present in array")
: printf("Element is present at index %d",
result);
return0;
}
sorting means arranging the given elements in sorting order i.e,, either ascending or descending
order.
Sorting algorithms are the algorithms meant for sorting the given elements i.e, either ascending
or descending order.
1.Bubble sort
2.Insertion sort
3.Selection sort
Bubble sort:
Example:
We take an unsorted array for our example. Bubble sort takes Ο(n 2) time so we're keeping it
short and precise.
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.
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 −
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.
Algorithm:
We assume list is an array of n elements. We further assume that swap function swaps the
values of the given array elements.
beginBubbleSort(list)
for all elements of list
if list[i]> list[i+1]
swap(list[i], list[i+1])
endif
endfor
return list
endBubbleSort
loop = list.count;
for i =0 to loop-1do:
swapped =false
for j =0 to loop-1do:
endfor
if(not swapped)then
break
endif
endfor
voidswap(int*xp, int*yp)
{
inttemp = *xp;
*xp = *yp;
*yp = temp;
}
}
Sorted array:
11 12 22 25 34 64 90
Selection sort
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-
based algorithm in which the list is divided into two parts, the sorted part at the left end and the
unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the
entire list.
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 Ο(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.
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.
Following is a pictorial depiction of the entire sorting process −
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;
endif
endfor
end procedure
Program:
#include<stdio.h>
#include<stdbool.h>
#define MAX 7
int intArray[MAX]={4,6,3,2,1,9,7};
printf("=\n");
}
void display(){
int i;
printf("[");
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();
}
}
void 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 −
Output
Input Array: [4 6 3 2 1 9 7 ]
==================================================
Items swapped: [ 4, 1 ]
Iteration 1#:[1 6 3 2 4 9 7 ]
Items swapped: [ 6, 2 ]
Iteration 2#:[1 2 3 6 4 9 7 ]
Iteration 3#:[1 2 3 6 4 9 7 ]
Items swapped: [ 6, 4 ]
Iteration 4#:[1 2 3 4 6 9 7 ]
Iteration 5#:[1 2 3 4 6 9 7 ]
Items swapped: [ 9, 7 ]
Iteration 6#:[1 2 3 4 6 7 9 ]
Output Array: [1 2 3 4 6 7 9 ]
==================================================
Funda is : Every time find the smallest element and place it in its position
https://www.youtube.com/watch?v=9oWd4VJOwr0 (source)
Time complexity in both best and worst cases is : O(n2)
Insetion sort:
It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.
Insertion sort moves ahead and compares 33 with 27.
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.
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.
Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted
Pseudocode
endfor
end procedure
Program:
Live Demo
#include<stdio.h>
#include<stdbool.h>
#define MAX 7
int intArray[MAX]={4,6,3,2,1,9,7};
printf("=\n");
}
void display(){
int i;
printf("[");
printf("]\n");
}
void insertionSort(){
int valueToInsert;
int holePosition;
int i;
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();
}
}
void 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 −
Output
Input Array: [4 6 3 2 1 9 7 ]
==================================================
Iteration 1#:[4 6 3 2 1 9 7 ]
item moved : 6
item moved : 4
item inserted : 3, at position : 0
Iteration 2#:[3 4 6 2 1 9 7 ]
item moved : 6
item moved : 4
item moved : 3
item inserted : 2, at position : 0
Iteration 3#:[2 3 4 6 1 9 7 ]
item moved : 6
item moved : 4
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 inserted : 7, at position : 5
Iteration 6#:[1 2 3 4 6 7 9 ]
Output Array: [1 2 3 4 6 7 9 ]
==================================================
Key Point:-We keep on dividing the current list into sorted and unsorted sub lists, we take one
element at a time from every new unsorted sublist and place it in a correct position in a every
new sorted list. We compare element in unsorted list with the elements of sorted list in reverse
direction to place in correct place.