0% found this document useful (0 votes)
6 views

CS112 Programming Languages 1 (Lecture 7 - Spring 2020)

This document covers search and sort algorithms, specifically focusing on Bubble Sort, Linear Search, and Binary Search. It explains the mechanics of Bubble Sort, including its implementation in C, and compares it to other sorting algorithms. Additionally, it introduces Linear and Binary Search techniques for finding elements in an array, highlighting the efficiency of Binary Search over Linear Search.

Uploaded by

zeyadzzzzsss
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)
6 views

CS112 Programming Languages 1 (Lecture 7 - Spring 2020)

This document covers search and sort algorithms, specifically focusing on Bubble Sort, Linear Search, and Binary Search. It explains the mechanics of Bubble Sort, including its implementation in C, and compares it to other sorting algorithms. Additionally, it introduces Linear and Binary Search techniques for finding elements in an array, highlighting the efficiency of Binary Search over Linear Search.

Uploaded by

zeyadzzzzsss
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/ 41

CS112 – Level 1

Programming Languages 1
( General Division – Software Engineering Program – Medical Informatics Program )

Lecture 7
Search and Sort Algorithms [ Part 1 ]
Bubble Sort, Linear Search, .. & .. Binary Search
Spring 2020 (Semester 2)
Week 8
Course & Lectures are based on their counterparts in the following courses:
o Harvard University's CS50; An introduction to the intellectual enterprises of
computer science and the art of programming, Harvard School of
Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New
South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++
(2011), and 6.S096 Introduction to C and C++ (2013), MIT (Massachusetts
1
Institute of Technology) OpenCourseWare.
2

• Sorting Arrays (Sort Algorithms)


O
u • Bubble Sort
t
l • Searching Arrays (Search Algorithms)
Outline i
n • Linear Search
e
• Binary search

2
Some Popular Sorting Algorithms:
• Bubble Sort
• Selection Sort
• Insertion Sort
• Merge Sort
• Quick Sort
• Heap Sort

In computer science, a sorting algorithm is an algorithm that puts


elements of a list in a certain order.

Sort Algorithms
So, Sorting takes an unordered collection and makes it an
ordered one.
Bubble
Sort

4
Bubble sort is one way to sort an array of numbers. Adjacent
values are swapped until the array is completely sorted. This
algorithm gets its name from the way values eventually "bubble"
up to their proper position in the sorted array.

o While stepping through the data, if two adjacent values are


not in sorted order, then swap them. After a full scan of the
array, repeat from step 1 if any changes have been made.

Sort Algorithms
Bubble Sort
o The algorithm can be used to sort a list in either ascending or
descending order.
Let's sort the elements of this array in ascending order.

0 1 2 3

8 6 4 2
First Pass: 3 Swaps
During our first pass through
the array, we've swapped (8,6),
0 1 2 3
(8,4), and (8,2). The value 8 has
"bubbled" up to its correct
position.
8 6 4 2
0 1 2 3

6 8 4 2
0 1 2 3

6 4 8 2
Second Pass: 2 Swaps
During our second pass, we've
swapped (6,4) and (6,2). The
0 1 2 3
value 6 has "bubbled" up to its
correct position. 6 4 2 8
0 1 2 3

4 6 2 8
0 1 2 3

4 2 6 8
Third Pass: 1 Swap
During our third pass, we've
swapped (4,2). The value 4 has
0 1 2 3
"bubbled" up to its correct
position. 4 2 6 8
0 1 2 3

2 4 6 8
0 1 2 3

2 4 6 8
Fourth Pass: 0 Swaps
On this final pass through the
list no swaps were made,
0 1 2 3
signaling that the array has
been completely sorted. 2 4 6 8
0 1 2 3

2 4 6 8
0 1 2 3

2 4 6 8
And this is how you can implement bubble sort in C to sort an array in
an ascending order.

Algorithm
initialize counter
do
{
set counter to 0

iterate through entire array


if array[n] > array[n+1]
swap them
increment counter
}
while (counter > 0)
What change would you make to this pseudocode if you wanted to sort
a list in descending order instead?
Sorting Algorithms: Bubble Sort ..
Example 1:
The bubble sort traverses a collection of elements:
o Move from the front to the end
o “Bubble” the largest value to the end using pair-wise
comparisons and swapping

1 2 3 4 5 6

77 42 35 12 101 5
Sorting Algorithms: Bubble Sort ..
Example 1:
The bubble sort traverses a collection of elements:
o Move from the front to the end
o “Bubble” the largest value to the end using pair-wise
comparisons and swapping

1 2 3 4 5 6

7742 Swap4277 35 12 101 5


Sorting Algorithms: Bubble Sort ..
Example 1:
The bubble sort traverses a collection of elements:
o Move from the front to the end
o “Bubble” the largest value to the end using pair-wise
comparisons and swapping

1 2 3 4 5 6

42 7735 Swap3577 12 101 5


Sorting Algorithms: Bubble Sort ..
Example 1:
The bubble sort traverses a collection of elements:
o Move from the front to the end
o “Bubble” the largest value to the end using pair-wise
comparisons and swapping

1 2 3 4 5 6

42 35 7712 Swap12
77 101 5
Sorting Algorithms: Bubble Sort ..
Example 1:
The bubble sort traverses a collection of elements:
o Move from the front to the end
o “Bubble” the largest value to the end using pair-wise
comparisons and swapping

1 2 3 4 5 6

42 35 12 77 101 5

No need to swap
Sorting Algorithms: Bubble Sort ..
Example 1:
The bubble sort traverses a collection of elements:
o Move from the front to the end
o “Bubble” the largest value to the end using pair-wise
comparisons and swapping

1 2 3 4 5 6

42 35 12 77 1015 Swap 101


5
Sorting Algorithms: Bubble Sort ..
Example 1:
The bubble sort traverses a collection of elements:
o Move from the front to the end
o “Bubble” the largest value to the end using pair-wise
comparisons and swapping

1 2 3 4 5 6

42 35 12 77 5 101

Largest value correctly placed


Sorting Algorithms: Bubble Sort ..
Example 2:
Swap Operation

One Pass:

The array after


the completion
of ALL passes:
Sorting Algorithms: Bubble Sort ..
Example 2:
E.g., swapping the first two
elements of an array:
temp = M[0];
M[0] = M[1];
M[1] = temp;
Bubbling the largest element up:
# define SIZE 5
for ( i = 0; i < 4 SIZE - 1 ; i++ ) {
if ( M[ i ] > M[ i + 1 ] ) { // in an ascending order
temp = M[ i ]; 20
M[ i ] = M[ i + 1 ];
M[ i +1 ] = temp; } }
Sorting Algorithms: Bubble Sort ..
Example 2:
How to mange each pass ..?

The array after


the completion
of ALL passes:

/* loop to control the number of passes */


for ( pass = 1; pass < SIZE; pass++ ) {
// loop to control the number of comparisons per pass
for ( i = 0; i < SIZE - pass; i++ ) {
......
}
}
Sorting Algorithms: Bubble Sort ..
Source Code:

// See the complete code in fig. 6.15 p.265-66


/* loop to control the number of passes */
for ( pass = 1; pass < SIZE; pass++ ) {
// loop to control the number of comparisons per pass
for ( i = 0; i < SIZE - pass ; i++ ) {
if ( a[ i ] > a[ i + 1 ] )
{
temp = a[ i ];
a[ i ] = a[ i + 1 ];
a[ i + 1 ] = temp;
}
} Bubble sort is the simplest sorting technique: 22

} ➔ it’s quite slow (requires larger run-time)


➔ Higher complexity
Sorting Algorithms: Bubble Sort ..
Bubble Sort Function using an Array

void bubbleSort (int a[], int size) {


int pass, temp, i;
for ( pass = 1; pass < SIZE; pass++ ) {
for ( i = 0; i < SIZE - pass; i++ )
{
if ( a[ i ] > a[ i + 1 ] )
{
temp = a[ i ];
a[ i ] = a[ i + 1 ];
a[ i + 1 ] = temp;
}
}
23
}
} // Main function call
bubbleSort( array, 5 );
Sorting Algorithms: Bubble Sort ..
Bubble Sort Function using an Array
The Array is Passed-by-Reference from the Main function

int main( void )


{
int array[ ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int i; // counter

bubbleSort( array, 10 ); // sort the array

puts( "\nData items in an ascending order:\n" );


for ( i = 0; i < 10; ++i ) {
printf( "%4d ", array[ i ] );
} 24
}
Data items in an ascending order:
2 4 6 8 10 12 37 45 68 89
Sorting Algorithms: Bubble Sort ..
Bubble Sort Function
Can we write a function for swapping? What will the
parameters of that function be?
void bubbleSort (int a[], int size){
unsigned int pass; int hold; int i;
for ( pass = 1; pass < SIZE; pass++ ) {
for ( i = 0; i < SIZE - pass; i++ ) {
if ( a[ i ] > a[ i + 1 ] ) {
hold = a[ i ];
a[ i ] = a[ i + 1 ];
a[ i + 1 ] = hold;
}
}
} 25

}
Sorting Algorithms: Bubble Sort ..
the Swap Function within the Bubble Sort
Can we write a function for swapping? What will the
parameters of that function be?

void swap( int *element1Ptr, int *element2Ptr )


{
int temp;
temp = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = temp;
}

26
Sorting Algorithms: Bubble Sort ..
the Bubble Sort using the Swap Function

void bubbleSort ( int * a , int size )


{ int a[] is equivalent to int *a
int pass, i;
for ( pass = 0; pass < size - 1; ++pass ) {
for ( i = 0; i < size - pass; ++i ) { Using the array
subscript notation
if ( a[ i ] > a[ i + 1 ] ) {
swap( &a[ i ], &a[ i + 1 ] );
}
} Must be called by-reference
}
} 27
Search
Algorithms

28
Search Algorithms: Searching an Array ..

o It may be necessary to determine whether an array contains a


value that matches a certain key value (or search key).
o The process of finding a particular element of an array is called
searching.
o We will discuss two searching techniques:
o The simple linear search technique, and ..
o The more efficient (but more complex) binary search
technique. 29
Search Algorithms: Linear Search ..

// Main function call


Element = linearSearch( a, searchKey, SIZE );

// See the complete code in fig. 6.18 p.272-73


int linearSearch( const int array[], int key, int size )
{ Can’t change array values
int n;
for ( n = 0; n < size; ++n ) {
if ( array[ n ] == key ) {
return n; /* return the location of key */
}
} 30
return -1; /* key not found */
}
Binary Search ..?

Back in the days when phone numbers weren’t stored in cell phones, you might
have actually had to look them up in a phonebook. How did you go about that?
If you wanted to look up someone with the last name “Smith,” you could flip
through the phonebook one page at a time ( linear search?! ). You don’t need to
be a computer scientist to know that this is an inefficient approach.

Instead, we could start by flipping to the middle of the phonebook, and let's say
we turn to a page with "M" on it. Since we know "Smith" comes after "Mike," we
can literally tear the phonebook in half, throw away the left half of the
phonebook, and leave ourselves with only the right half. We've just broken the
problem in two!

Once again, we flip to the middle and find ourselves at “R.” We can again throw
away the left half. As we continue tearing the book in half and throwing away
pieces of it, we will eventually be left with a single page on which the name
“Smith” appears (assuming it was there in the first place).
Binary Search ..
Does the array contain 7?
We can apply the same logic to searching for a value in an
array of sorted numbers.

0 1 2 3 4 5 6

1 3 5 6 7 9 10
Binary Search ..

0 1 2 3 4 5 6

1 3 5 6 7 9 10
We see that array[3] is 6, which is < 7.

Is array[3] == 7?
Is array[3] < 7?
Is array[3] > 7?
So, just as we tore off half the phone book, we can now
disregard the entire left half of this array.
Binary Search ..

0 1 2 3 4 5 6

1 3 5 6 7 9 10
Next, check the value stored at the middle index of what's
left of the array. We can see that array[5] is 9, which is > 7.
Is array[5] == 7?
Is array[5] < 7?
Is array[5] > 7?
This time, we'll discard the right portion of what's left of
the array.
Binary Search ..

0 1 2 3 4 5 6

1 3 5 6 7 9 10
array[4] == 7! We've found the value we were searching
for!
Is array[4] == 7?
Is array[4] < 7?
Is array[4] > 7?
Note however, that this array was presorted ..
low → low index in range
Binary Search .. high → high index in range
middle= (low+ high)/2
low high middle high Integer
low
division
0 1 2 3 4 5 6 7 8 9
Sorted
5 17 35 59 77 79 83 90 92 120
array
key < a [middle] key > a [middle]
= Key
high = middle - 1 low = middle + 1

Return middle
It is required to find the index of Key in the array
If Key == a[middle] then Return middle
Otherwise, If Key < a[middle] then Search in the left part of a
Otherwise, Search in the right part of a
And So On …
Note that: 36

One-half of the elements in a sorted array are eliminated from


consideration after each comparison.
low → low index in range
Binary Search .. high → high index in range
middle= (low+ high)/2
low middle high Integer
low
division
0 1 2 3 4 5 6 7 8 9
5 17 35 59 77 79 83 90 92 120 Key
key > a [middle] 79
low = middle + 1
Middle
low high high Low high
Middle
5 6 7 8 9 5 6
79 83 90 92 120 79 83
Key < a [middle] Key == a [middle]
high = middle - 1 Return Middle

37

In this example, it returns the index 5 after only 3 comparisons ..


Binary Search: an Iterative Approach
// Main function call
result = binarySearch( a, key, 0, SIZE-1 );
// See the complete code in fig. 6.19 p.274-75
int binarySearch( const int b[], int searchKey, int low, int high ) {
int middle;
while ( low <= high ) {
middle = ( low + high ) / 2;
if ( searchKey == b[ middle ] )
return middle;
else if ( searchKey < b[ middle ] )
high = middle – 1;
else low = middle + 1;
} /* end while */ 38

return -1; /* searchKey not found */


}
Binary Search: a Recursive Approach
// Main function call
result = binarySearch( a, key, 0, SIZE-1 );
int binarySearch( const int b[], int Key, int low, int high ) {
if ( low > high ) return -1; //Base Case

int middle = ( low + high ) / 2;


if ( b[ middle ] == Key) return middle; //Base Case

if ( searchKey < b[ middle ] )


// Search in the left part of the array
return binarySearch( b, Key, low, middle-1 );
else
// Search in the right part of the array 39

return binarySearch( b, Key, middle + 1, high );


}
Binary Search: an Example
Trace the values of: low mid high
.. low, mid, and high. 0 5 10
6 8 10
6 6 7
If we search for 79 6 5

0 1 2 3 4 5 6 7 8 9 10 Low > high


➔stop (return -1)
5 17 35 59 77 78 80 85 90 92 97
80 85 92 2 97
80 85
80

Section 6.8
40
Thanks! .. Questions?

41

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

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:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy