You are on page 1of 16

SORTING AND CHAPTER 1

SEARCHING
(PART 2)
SORTING
• Bubble sort is known as the simplest sorting algorithm.
• In bubble sort, array is traversed from first element to
last element.
• The current element is compared with the next
element.
BUBBLE • If current element is greater than the next element,
SORT it is swapped.

• Example:
• We can create a Java program to sort array
elements using bubble sort.
BUBBLE SORT
(CONT..)

How it works?
(First example)
BUBBLE SORT
(CONT..)

How it works?
(Second example)

This process will be repeated until all numbers are sorted.


void bubbleSort (int [ ] arr) {  
int n = arr.length;  
BUBBLE int temp = 0;  

SORT for (int i=0; i < arr.length; i++) {  


for (int j=1; j < (n - i); j++) {  
(CONT..) if (arr [ j-1] > arr [ j ]) {  
//swap elements  
temp = arr [ j-1];  
arr [ j-1] = arr [ j ];  
The source code arr [ j ] = temp;  
}    
}  
}  
INSERTION SORT

• In insertion sort algorithm, an array is searched sequentially and unsorted elements are
moved and inserted into the sorted sub-list in the same array.

• This algorithm is not suitable for large data sets because it requires more time for sorting
large number of elements.
INSERTION SORT (THE ALGORITHM)
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
INSERTION
SORT (CONT..)

How it works?
int i, j, key;
INSERTION for (i = 1; i < length; i++)
SORT (CONT..) {
j = i;
while (j > 0 && arr [j - 1] > arr [ j ])
{
key = arr [ j];
Source code arr[j] = arr [ j - 1];
arr [ j - 1] = key;
j--;
}
}
SEARCHING
BINARY SEARCH
• Binary search is a fast search algorithm that works on the principle of divide and conquer.
• To make the algorithm to work properly, the data should be in the sorted form.
• Binary search looks for a particular item by comparing the middle most item in the data collection.
• If a match occurs, then the index of the item is returned.
• If the middle item is greater than the item, then the item is searched in the sub-array to the left of
the middle item. 

• Otherwise, the item is searched for in the sub-array to the right of the middle item. This process
continues on the sub-array as well until the size of the subarray reduces to zero.
HOW BINARY SEARCH WORKS?

• For a binary search to work, it is mandatory for the target array to be sorted. We shall
learn the process of binary search with a pictorial example. The following is our sorted
array and let us assume that we need to search the location of value 31 using binary
search.

You might also like