0% found this document useful (0 votes)
53 views22 pages

DSA CH 2

The document discusses various sorting algorithms: 1) Insertion sort works by taking each element and inserting it into the sorted portion of the array by comparing it to all previous elements. This requires N passes to fully sort an array of N elements. 2) Selection sort works by selecting the smallest element in each pass and swapping it into the correct position. This requires N-1 passes to sort an array of N elements. 3) Bubble sort compares adjacent elements and swaps them if out of order, causing the largest elements to "bubble" to the end with each pass. This takes N-1 passes to fully sort an array. 4) Pointer sort demonstrates how to access and sort

Uploaded by

amanuel29831
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views22 pages

DSA CH 2

The document discusses various sorting algorithms: 1) Insertion sort works by taking each element and inserting it into the sorted portion of the array by comparing it to all previous elements. This requires N passes to fully sort an array of N elements. 2) Selection sort works by selecting the smallest element in each pass and swapping it into the correct position. This requires N-1 passes to sort an array of N elements. 3) Bubble sort compares adjacent elements and swaps them if out of order, causing the largest elements to "bubble" to the end with each pass. This takes N-1 passes to fully sort an array. 4) Pointer sort demonstrates how to access and sort

Uploaded by

amanuel29831
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Chapter 2

Simple Sorting and Searching Algorithms


Sorting algorithms commonly consist of two types of operation: comparisons and data
movements. A comparison is simply comparing one value in a list with another, and a data
movement (swapping) is an assignment.

Why do we study sorting and searching algorithms?

they are the most common & useful tasks in any software development

they take more than 25% of running time of computers task

Example:
 Searching documents over the internet
 Searching files and folders in a hard disk
 Sorting students by their name, year and so on
 Sorting file, search results by file name, date created and so on
 Deleting and recording data from a database

Insertion Sort
In the insertion sort technique, we start from the second element and compare it with the first
element and put it in a proper place. Then we perform this process for the subsequent elements.

We compare each element with all its previous elements and put or insert the element in its
proper position.

The array to be sorted is as follows:

1|Page
Now for each pass, we compare the current element to all its previous elements. So in the first
pass, we start with the second element.

2|Page
Thus we require N number of passes to completely sort an array containing N number of
elements.

The above illustration can be summarized in a tabular form:

Pass Unsorted list comparison Sorted list


1 {12,3,5,10,8,1} {12,3} {3,12,5,10,8,1}
2 {3,12,5,10,8,1} {3,12,5} {3,5,12,10,8,1}
3 {3,5,12,10,8,1} {3,5,12,10} {3,5,10,12,8,1}
4 {3,5,10,12,8,1} {3,5,10,12,8} {3,5,8,10,12,1}
5 {3,5,8,10,12,1} {3,5,8,10,12,1} {1,3,5,8,10,12}
6 {} {} {1,3,5,8,10,12}

As shown in the above illustration, we begin with the 2nd element as we assume that the first
element is always sorted. So we begin with comparing the second element with the first one and
swap the position if the second element is less than the first.

This comparison and swapping process positions two elements in their proper places. Next, we
compare the third element to its previous (first and second) elements and perform the same
procedure to place the third element in the proper place.

In this manner, for each pass, we place one element in its place. For the first pass, we place the
second element in its place. Thus in general, to place N elements in their proper place, we need
N-1 passes.

Next, we will demonstrate the Insertion sort technique implementation in C++ language.

#include<iostream>
using namespace std;
int main ()
{
int myarray[6] = { 12,3,5,10,8,1};

3|Page
cout<<"\nInput list is \n";
for(int i=0;i<6;i++)
{
cout <<myarray[i]<<"\t";
}
for(int k=1; k<6; k++)
{
int temp = myarray[k];
int j= k-1;
while(j>=0 && temp <= myarray[j])
{
myarray[j+1] = myarray[j];
j = j-1;
}
myarray[j+1] = temp;
}
cout<<"\nSorted list is \n";
for(int i=0;i<6;i++)
{
cout <<myarray[i]<<"\t";
} }

Analysis
Pass number of comparison number of swaps
1 1 1
2 2 2
. . .
. . .
. . .
n-1 n-1 n-1
Total n(n-1)/2 n(n-1)/2
It is in O(n2)

4|Page
Selection Sort
As the name itself suggests, the selection sort technique first selects the smallest element in the
array and swaps it with the first element in the array.

Next, it swaps the second smallest element in the array with the second element and so on. Thus
for every pass, the smallest element in the array is selected and put in its proper position until the
entire array is sorted.

An example to illustrate this selection sort algorithm is shown below.

Illustration

5|Page
6|Page
The tabular representation for this illustration is shown below:

Unsorted list Least element Sorted list

{18,10,7,20,2} 2 {}

{18,10,7,20} 7 {2}

{18,10,20} 10 {2,7}

{18,20} 18 {2,7,10)

{20} 20 {2,7,10,18}

{} {2,7,10,18,20}

From the illustration, we see that with every pass the next smallest element is put in its correct
position in the sorted array. From the above illustration, we see that in order to sort an array of 5
elements, four passes were required. This means in general, to sort an array of N elements, we
need N-1 passes in total.

Given below is the implementation of selection sort algorithm in C++.

#include<iostream>

using namespace std;

7|Page
int findSmallest (int[],int);

int main ()

int myarray[10] = {18,10,7,20,2};

int pos,temp,pass=0;

cout<<"\n Input list of elements to be Sorted\n";

for(int i=0;i<5;i++)

cout<<myarray[i]<<"\t";

for(int i=0;i<5;i++)

pos = findSmallest (myarray,i);

temp = myarray[i];

myarray[i]=myarray[pos];

myarray[pos] = temp;

pass++;

cout<<"\n Sorted list of elements is\n";

8|Page
for(int i=0;i<5;i++)

cout<<myarray[i]<<"\t";

cout<<"\nNumber of passes required to sort the array: "<<pass;

return 0;

int findSmallest(int myarray[],int i)

int ele_small,position,j;

ele_small = myarray[i];

position = i;

for(j=i+1;j<5;j++)

if(myarray[j]<ele_small)

ele_small = myarray[j];

position=j;

9|Page
}

return position;

Analysis

Pass number of comparison number of swaps

1 n-1 n-1

2 n-2 n-2

. . .

. . .

. . .

n-1 1 1

total n(n-1)/2 n-1

It is in O(n2)

Bubble Sort
Bubble Sort is the simplest of the sorting techniques.

In the bubble sort technique, each of the elements in the list is compared to its adjacent element.
Thus if there are n elements in list A, then A[0] is compared to A[1], A[1] is compared to A[2]
and so on.

10 | P a g e
After comparing if the first element is greater than the second, the two elements are swapped
then.

We take an array of size 5 and illustrate the bubble sort algorithm.

11 | P a g e
12 | P a g e
Array entirely sorted.

The above illustration can be summarized in a tabular form as shown below:

Pass Unsorted list comparison Sorted list


1 {10,5,15,0,12} {10,5} {5,10,15,0,12}
{5,10,15,0,12} {10,15} {5,10,15,0,12}
{5,10,15,0,12} {15,0} {5,10,0,15,12}

13 | P a g e
Pass Unsorted list comparison Sorted list
{5,10,0,15,12} {15,12} {5,10,0,12,15}
2 {5,10,0,12,15} {5,10} {5,10,0,12,15}
{5,10,0,12,15} {10,0} {5,0,10,12,15}
{5,0,10,12,15} {10,12} {5,0,10,12,15}
3 {5,0,10,12,15} {5,0} {0,5,10,12,15}
{5,0,10,12,15} {5,10} {5,0,10,12,15}
{5,0,10,12,15} SORTED

As shown in the illustration, with every pass, the largest element bubbles up to the last thereby
sorting the list with every pass. As mentioned in the introduction, each element is compared to its
adjacent element and swapped with one another if they are not in order.

Thus as shown in the illustration above, at the end of the first pass, if the array is to be sorted in
ascending order, the largest element is placed at the end of the list. For the second pass, the
second largest element is placed at the second last position in the list and so on.

When we reach N-1 (where N is a total number of elements in the list) passes, we will have the
entire list sorted.

#include<iostream>

using namespace std;

int main ()

int i, j,temp,pass=0;

int a[10] = {10,5,15,0,12};

cout <<"Input list ...\n";

for(i = 0; i<5; i++) {

14 | P a g e
cout <<a[i]<<"\t";

cout<<endl;

for(i = 0; i<5; i++) {

for(j = i+1; j<5; j++)

if(a[j] < a[i]) {

temp = a[i];

a[i] = a[j];

a[j] = temp;

}}

pass++;

cout <<"Sorted Element List ...\n";

for(i = 0; i<5; i++) {

cout <<a[i]<<"\t";

cout<<"\nNumber of passes taken to sort the list:"<<pass<<endl;

return 0;}

Analysis
Passes number of comparison number of swaps

1 n-1 n-1

2 n-2 n-2

15 | P a g e
. . .

. . .

. . .

n-1 1 1

total n(n-1)/2 n(n-1)/2

=O(n2)

Pointer sort
The array can be fetched with the help of pointers with the pointer variable pointing to the base
address of the array. Hence in order to sort the array using pointers, we need to access the
elements of the array using (pointer + index) format.

#include<iostream.h>

void sort(int,int*);

int main()

int n = 5;

int arr[] = { 0, 23, 14, 12, 9 };

sort(n, arr);

return 0;

void sort(int n, int* ptr)

int i, j, t,pass=0;

// Sort the numbers using pointers


16 | P a g e
for (i = 0; i < n; i++) {

for (j = i + 1; j < n; j++) {

if (*(ptr + j) < *(ptr + i)) {

t = *(ptr + i);

*(ptr + i) = *(ptr + j);

*(ptr + j) = t;

pass++;

// print the numbers

for (i = 0; i < n; i++)

cout<<*(ptr + i);

0 23 14 12 9

i=0 0<5 true

j=1 23<0 j=2 14<0 j=3 12<0 j=4 9<0 j=5 false

i=1

j=2 14<23 true [0 14 23 12 9] j=3 12<14 true [0 12 23 14 9] j=4 9<12 true [0 9 23 14 12 ] j=5
false

i=2

j=3 14<23 true [0 9 14 23 12] j=4 12<14 true [0 9 12 23 14] j=5 false

i=3

17 | P a g e
j=4 14<23 true [0 9 12 14 23]

Sequential Search
Sequential search in C++ is also called a linear search. This searching technique is very simple,
to perform this technique the user starts the loop from the zero index of an array to the last index
of an array. It starts from the first index and compared the required value with the first value.

If the required value is found it will show the result otherwise compare the value of next index
and it will continue until the required value is found or loop completes without finding any
value.

#include<iostream>

using namespace std;

int main()

int arr[5], i, num, index;

cout<<"Enter 5 Numbers: ";

for(i=0; i<5; i++)

cin>>arr[i];

cout<<"\nEnter a Number to Search: ";

cin>>num;

for(i=0; i<5; i++)

18 | P a g e
if(arr[i]==num)

index=i;

cout<<"Found element"<<num<<"at index"<<i;

return 0;

The maximum number of comparison is n, i.e. O (n).

Binary Search
Binary search is a mechanism used to find the given elements from the sorted array by
continuously halving the array and then searching specified elements from a half array. And the
process goes on till the match is found. It works only the sorted data structures. The time
complexity of the binary search algorithm is O (log n).

#include<iostream>

using namespace std;

int main()

int i, arr[10], num, first, last, middle;

cout<<"Enter 10 Elements (in ascending order): ";

for(i=0; i<10; i++)

19 | P a g e
cin>>arr[i];

cout<<"\nEnter Element to be Search: ";

cin>>num;

first = 0;

last = 9;

middle = (first+last)/2;

while(first <= last)

if(arr[middle]<num)

first = middle+1;

else if(arr[middle]==num)

cout<<"\nThe number, "<<num<<" found at Position "<<middle+1;

break;

else

last = middle-1;

middle = (first+last)/2;

if(first>last)

cout<<"\nThe number, "<<num<<" is not found in given Array";

cout<<endl;

return 0;

20 | P a g e
}

5 7 9 13 32 33 42 54 56 88

Key=33

First=0 last=9 middle=first+last/2=0+9/2=4

33>A[middle]

33>A[4]

33>32 First=middle+1

33 42 54 56 88

First=5 last=9 middle=first+last/2=5+9/2=7

33<A[middle]

33<A[7]

33<54 last=middle-1

33 42

First=5 last=6 middle=first+last/2=5+6/2=5

33==A[middle]

33==A[5]

33==33

Time complexity of binary search

Let assume the value of N is 8

1st comparison 8/2=4

2nd comparison 4/2=2

21 | P a g e
3rd comparison 2/2=1

8/21=4

8/22=2 =N/2k=1

8/23=1

N/2k=1

N=2k

log2N=log22k

K= log2N O(log2N)

22 | P a g e

You might also like