Day 5 - Basic Algorithms

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 46

Major Data

Structure
Algorithms
What’s algorithms?
Objectives Search Algorithms
Sorting Algorithms
Algorithms
 A finite sequence of rigorous instructions, typically used to solve a class of
specific problems or to perform a computation.

 a specific procedure for solving a well-defined computational problem

 Example:
Ethiopian binary math:
a Shaman in Ethiopian villages:1941
 Algorithms provide step by step instructions on solving specific problems. They
help you solve problems using efficient, standard, and reusable steps
Searching Algorithms
 Searching in data structure refers to the process of finding the required
information from a collection of items stored as elements in the computer
memory.
 Based on the type of search operation, these algorithms are generally classified
into two categories:
1. Sequential Search: In this, the list or array is traversed sequentially and every
element is checked. For example: Linear Search.
2. Interval Search: These type of searching algorithms are much more efficient
than Linear Search as they repeatedly target the center of the search
structure and divide the search space in half. For Example: Binary Search.
Linear Search in Java
 Algorithm:

Step 1: Traverse the array

Step 2: Match the key element with


array element

Step 3: If key element is found, return


the index position of the array element

Step 4: If key element is not found,


return -1 (for more: Linear Search)
Example: Search where 1 is located
 Linear search is a sequential searching algorithm where we start from one end
and check every element of the list until the desired element is found. It is the
simplest searching algorithm.
 Example:
Start from the first element, compare k with each
element x
 Compare with each element
If x == k, return the index
 Element found? Return index.
Code in Java
int linearSearch(int[] numsArray, int key) {

for (int index = 0; index < numsArray.length; index++){


if (key == numsArray[index]) {
return index;
}
}
return -1;
}
Binary Search in Java [Divide & Conquer]
 In binary search, array elements must be in ascending order. If you have
unsorted array, you can sort the array using Arrays.sort(arr) method.
 It is used to search and find an element in a sorted array.

 Algorithm:
1. Compare x with the middle element.
2. If x matches with the middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in the right half
subarray after the mid element. So we recur for the right half.
4. Else (x is smaller) recur for the left half.
Binary Search
steps
 Sort the Array
Assume we're looking for is 13
 Choose Low and High Values
 The first index of the array will be denoted as low while the highest index will
be denoted as high.
Choose Midpoint/Middle Element
 Midpoint = (low + high) / 2.
Now the search begins
 If Key item (number_to_search_for) is equal to midpoint, the midpoint index
will be returned.

 If Key item is greater than midpoint, search through the elements on the right
side of the midpoint.

 If Key item is less than midpoint, search through the elements on the left side
midpoint.
Iteration #1
Iteration #2
Code in Java
int binarySearch(int[] numsArray, int key) {
int lowIx = 0;
int highIx = numsArray.length - 1;
while (lowIx <= highIx) {
int midIx = (lowIx + highIx) / 2;
if (key == numsArray[midIx]) {
return midIx;
}
if (key < numsArray[midIx]) {
highIx = midIx - 1;
}
if (key > numsArray[midIx]) {
lowIx = midIx + 1;
}

}
return -1;
} // In a case where the element doesn't exist, -1 will be returned
Sorting Algorithms
 A Sorting Algorithm is used to rearrange a given array or list elements according
to a comparison operator on the elements. The comparison operator is used to
decide the new order of element in the respective data structure.

 You can use various ordering criteria, common ones being sorting numbers
from least to greatest or vice-versa
Types of Sorting Algorithm
 There are numerous types of sorting in data structures some of which are
1. Bubble Sort
2. Selection sort
3. Insertion sort
4. Merge sort
Selection Sort
 Selection Sort also divides the array into a sorted and unsorted subarray.
Though, this time, the sorted subarray is formed by inserting the minimum
element of the unsorted subarray at the end of the sorted array, by swapping.

 Example of Selection sort


(20 12 10 15 2)
Selection Sort
 The selection sort algorithm sorts an array by repeatedly finding the minimum
element (considering ascending order) from unsorted part and putting it at the
beginning.
 The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering
ascending order) from the unsorted subarray is picked and moved to the
sorted subarray.
Working of selection sort
1. Set the first element as minimum
2. Compare minimum with the second element. If the second element is smaller
than minimum, assign the second element as minimum
3. Compare minimum with the third element. Again, if the third element is smaller,
then assign minimum to the third element otherwise do nothing. The process goes
on until the last element.
 After each iteration, minimum is placed in the front of the unsorted list
Bubble Sort : Walia FC Players line up
.
How to bubble the longest
Here are the rules :
1. Compare two players.

2. If the one on the left is taller,


swap them.

3. Move one position right.


4. When you reach the first sorted
player, start over @the left end of
the line.
 You continue down the line this way until you reach the right end. You have by
no means finished sorting the players, but you do know that the tallest player is
on the right. This must be true because, as soon as you encounter the tallest
player, you’ll end up swapping him (or her) every time you compare two
players, until eventually he (or she) will reach the right end of the line. This is
why it’s called the bubble sort:

As the algorithm progresses, the biggest items “bubble up” to the top end of
the array.
The end of the 1st pass
.
 After this first pass through all the data, you’ve made N-1 comparisons and
somewhere between 0 and N-1 swaps, depending on the initial arrangement of
the players. The item at the end of the array is sorted and won’t be moved
again. Now you go back and start another pass from the left end of the line.
Again, you go toward the right, comparing and swapping when appropriate.

 However, this time you can stop one player short of the end of the line, at
position N-2, because you know the last position, at N-1, already contains the
tallest player
Bubble sort
 Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping
the adjacent elements if they are in wrong order.
 Example ( 5 1 4 2 8 )
Code in Java
public void bubblesort(int[] bubble) {
for(int i = bubble.length - 1; i >= 0; i--) {
for(int j = 0; j < i; j++) {
//do swap adjacent files after comparison
if(bubble[j] > bubble[j + 1]) {
int temp = bubble[j];
bubble[j] = bubble[j + 1];
bubble[j + 1] = temp;
}
}
}

}
Insertion Sort
 Insertion sort is a simple sorting algorithm that works similar 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 at the correct position in the sorted part.

 Algorithm
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to the elements
before. Move the greater elements one position up to make space for the
swapped element.
Insertion Sort: Have you ever played cards?
Example
logic
public void sort(int [] numbers) {
for(int i= 1; i < numbers.length; i++) {
int key = numbers[i];
int j = i - 1;

while(j >= 0 && numbers[j] > key) {


numbers[j + 1] = numbers[j];
j = j - 1;
}
numbers[j + 1] = key;
}
}
Merge Sort
Merge sort is a divide and conquer
algorithm that divides the input array into
two halves, recursively sorts each half, and
then merges the sorted halves to produce
the final sorted array.
// Merge Sort function
public void mergeSort(int[] array) {
if (array.length <= 1) {
return; // Base case: array with 0 or 1 element is already sorted
}
// Divide the array into two halves
int mid = array.length / 2;
int[] leftArray = new int[mid];
int[] rightArray = new int[array.length - mid];
// Copy elements to left and right arrays
for (int i = 0; i < mid; i++) {
leftArray[i] = array[i];
}
for (int i = mid; i < array.length; i++) {
rightArray[i - mid] = array[i];
}
// Recursively sort the two halves
mergeSort(leftArray);
mergeSort(rightArray);
// Merge the sorted halves
merge(array, leftArray, rightArray);
}
// Merge function
public void merge(int[] array, int[] leftArray, int[] rightArray) {
int leftLength = leftArray.length;
int rightLength = rightArray.length;
int i = 0, j = 0, k = 0;
// Compare elements of left and right arrays and merge them into array
while (i < leftLength && j < rightLength) {
if (leftArray[i] <= rightArray[j]) {
array[k++] = leftArray[i++];
}
else {
array[k++] = rightArray[j++];
}
}
// Copy remaining elements of left array if any
while (i < leftLength) {
array[k++] = leftArray[i++];
}
// Copy remaining elements of right array if any
while (j < rightLength) {
array[k++] = rightArray[j++];
}
}
mergeSort(array)
 This is the main function of the merge sort algorithm.
 It first checks if the array has 0 or 1 elements, in which case it is already sorted,
so it returns.
 It then divides the array into two halves.
 It recursively calls mergeSort on the left and right halves.
 Finally, it merges the sorted halves using the merge function.
merge(array, leftArray, rightArray)
 This function takes three arrays as parameters: the original array, and the two
halves to be merged.
 It compares elements from the left and right arrays and merges them into the
original array in sorted order.
 It continues this process until one of the arrays is fully merged.
 Then, it copies any remaining elements from the other array into the original
array.
Quick Sort
 Quicksort is a sorting algorithm based on the divide and conquer
approach where
1.An array is divided into subarrays by selecting a pivot element (element
selected from the array).

While dividing the array, the pivot element should be positioned in such a way
that elements less than pivot are kept on the left side and elements greater than
pivot are on the right side of the pivot.
2.The left and right subarrays are also divided using the same approach. This
process continues until each subarray contains a single element.
3.At this point, elements are already sorted. Finally, elements are combined to
form a sorted array.
References
https://www.javatpoint.com/abstract-class-in-java
https://www.javatpoint.com/linear-search-in-java
https://stackabuse.com/sorting-algorithms-in-java/
https://www.javatpoint.com/binary-search-in-java
https://www.geeksforgeeks.org/bubble-sort/

You might also like