Beruflich Dokumente
Kultur Dokumente
Algorithm:
An algorithm is a step-by-step procedure or method for solving a problem by a computer in a given number of
steps. The steps of an algorithm may include repetition depending upon the problem for which the algorithm is
being developed. The algorithm is written in human readable and understandable form. To search an element in
a given array, it can be done in two ways Linear search and Binary search.
Linear search:
Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all
items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise
the search continues till the end of the data collection.
Algorithm:
Linear Search ( Array A, Value x)
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
Program:
import java.util.*;
class LinearSearch
{
public static void main(String args[])
{
int i, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
VENU-DRN
2
Binary Search:
Binary search is a fast search algorithm with run-time complexity of (log n). This search algorithm works on
the principle of divide and conquer. For this algorithm to work properly, the data collection should be in the
sorted form.Binary search looks for a particular item by comparing the middle most item of the collection. If a
match occurs, then the index of 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.
Binary Search is applied on the sorted array or list. In binary search, we first compare the value with the
elements in the middle position of the array. If the value is matched, then we return the value. If the value is
less than the middle element, then it must lie in the lower half of the array and if it's greater than the element
then it must lie in the upper half of the array. We repeat this procedure on the lower (or upper) half of the array.
Binary Search is useful when there are large numbers of elements in an array.
Algorithm:
Initialize first=0 and last=sortedArray.length-1
compute mid and compare sortedArray[mid] with element to be searched
If element to be searched is less than sortedArray[mid] then element lies in left part of the mid, so last=mid
if element to be searched is greater than sortedArray[mid] then element lies in right part of the mid, so
first=mid+1.
if element to be searched is equal to sortedArray[mid] , then return index
Repeat above process until first is less than last.
VENU-DRN
3
Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find that the value at
location 4 is 27, which is not a match. As the value is greater than 27 and we have a sorted array, so we also
know that the target value must be in the upper portion of the array.
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.
The value stored at location 7 is not a match, rather it is less than what we are looking for. So, the value must
be in the lower part from this location.
We compare the value stored at location 5 with our target value. We find that it is a match.
VENU-DRN
4
Pseudocode
The pseudocode of binary search algorithms should look like this
Procedure binary_search
A sorted array
n size of array
x value to be searched
Set lowerBound = 1
Set upperBound = n
while x not found
if upperBound < lowerBound
EXIT: x does not exists.
set midPoint = lowerBound + ( upperBound - lowerBound ) / 2
if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midPoint
end while
end procedure
Program
import java.util.*;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
SORTINGS
1.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.
VENU-DRN
6
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.
VENU-DRN
7
Algorithm:
Step 1 Set MIN to location 0
Step 2 Search the minimum element in the list
Step 3 Swap with value at location MIN
Step 4 Increment MIN to point to next element
Step 5 Repeat until list is sorted
Pseudocode:
procedure selection sort
list : array of items
n : size of list
for i = 1 to n - 1
/* set current element as minimum*/
min = i
/* check the element to be minimum */
for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for
/* swap the minimum element with the current element*/
if indexMin != i then
VENU-DRN
8
PROGRAM
public class SelectionSortExample
{
public static void selectionSort(int[] arr)
{
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
{
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
public static void main(String args[])
{
int arr1[] = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);//sorting array using selection sort
System.out.println("After Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
}
}
2.INSERTION SORT
This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted.
For example, the lower part of an array is maintained to be sorted. An element which is to be 'insert'ed in this
sorted sub-list, has to find its appropriate place and then it has to be inserted there. Hence the name, insertion
sort.
VENU-DRN
9
The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the
same array). This algorithm is not suitable for large data sets as its average and worst case complexity are of
(n2), where n is the number of items.
It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.
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.
VENU-DRN
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.
program
public class InsertionSortExample {
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
}
}
}
}
3.BUBBLE SORT
We can create a java program to sort array elements using bubble sort. Bubble sort algorithm is known as the
simplest sorting algorithm.In bubble sort algorithm, array is traversed from first element to last element. Here,
current element is compared with the next element. If current element is greater than the next element, it is
swapped. This algorithm is not suitable for large data sets as its average and worst case
complexity are of (n2) where n is the number of items.
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.
Next we compare 33 and 35. We find that both are in already sorted positions.
VENU-DRN
13
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.
VENU-DRN
14
begin BubbleSort(list)
return list
end BubbleSort
Pseudocode
We observe in algorithm that Bubble Sort compares each pair of array element unless the whole array is
completely sorted in an ascending order. This may cause a few complexity issues like what if the array needs
no more swapping as all the elements are already ascending.
To ease-out the issue, we use one flag variable swapped which will help us see if any swap has happened or
not. If no swap has occurred, i.e. the array requires no more processing to be sorted, it will come out of the
loop.
end for
/*if no number was swapped that means
array is sorted now, break the loop.*/
if(not swapped) then
break
end if
end for
end procedure return list
Program:
class BubbleSortExample
VENU-DRN
15
{
static void bubbleSort(int[] arr)
{
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
if(arr[j-1] > arr[j])
{
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String args[])
{
int arr[] ={3,60,35,2,45,320,5};
4.QUICK SORT
Quicksort or partition-exchange sort, is a fast sorting algorithm, which is using divide and conquer algorithm.
Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort
can then recursively sort the sub-lists.
Quick sort partitions an array and then calls itself recursively twice to sort the two resulting subarrays.
This algorithm is quite efficient for large-sized data sets as the complexity of quick sort in the average case is
O(n log(n)) and in the worst case is O(n2) where n is the number of items.
VENU-DRN
16
There are two indices i and j and at the very beginning of the partition algorithm i points to the first element in
the array and j points to the last one. Then algorithm moves i forward, until an element with value greater or
equal to the pivot is found. Index j is moved backward, until an element with value lesser or equal to the pivot
is found. If i j then they are swapped and i steps to the next position (i + 1), j steps to the previous one (j - 1).
Algorithm stops, when i becomes greater than j.
After partition, all values before i-th element are less or equal than the pivot and all values after j-th element
are greater or equal to the pivot.
VENU-DRN
17
Notice, that we show here only the first recursion step, in order not to make example too long. But, in fact, {1,
2, 5, 7, 3} and {14, 7, 26, 12} are sorted then recursively.
VENU-DRN
18
Algorithm:
Step 1 Choose the highest index value has pivot
Step 2 Take two variables to point left and right of the list excluding pivot
Step 3 left points to the low index
Step 4 right points to the high
Step 5 while value at left is less than pivot move right
Step 6 while value at right is greater than pivot move left
Step 7 if both step 5 and step 6 does not match swap left and right
Step 8 if left right, the point where they met is new pivot
PROGRAM
int i = lowerIndex;
int j = higherIndex;
// calculate pivot number, I am taking pivot as middle index number
int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
// Divide into two arrays
while (i <= j)
{
/**
* In each iteration, we will identify a number from left side which
* is greater then the pivot value, and also we will identify a number
* from right side which is less then the pivot value. Once the search
* is done, then we exchange both numbers.
*/
while (array[i] < pivot)
{
i++;
}
while (array[j] > pivot)
{
VENU-DRN
19
j--;
}
if (i <= j)
{
exchangeNumbers(i, j);
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j)
quickSort(lowerIndex, j);
if (i < higherIndex)
quickSort(i, higherIndex);
}
private void exchangeNumbers(int i, int j)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String args[])
{
MyQuickSort sorter = new MyQuickSort();
int[] input = {24,2,45,20,56,75,2,56,99,53,12};
sorter.sort(input);
for(int i:input){
System.out.print(i);
System.out.print(" ");
}
}
}
5.MERGE SORT
Merge sort is a sorting technique based on divide and conquer technique. With worst-case time complexity
being (n log n), it is one of the most respected algorithms.
Merge sort first divides the array into equal halves and then combines them in a sorted manner.
Procedure 1:
VENU-DRN
20
We know that merge sort first divides the whole array iteratively into equal halves unless the atomic values are
achieved. We see here that an array of 8 items is divided into two arrays of size 4.
This does not change the sequence of appearance of items in the original. Now we divide these two arrays into
halves.
We further divide these arrays and we achieve atomic value which can no more be divided.
Now, we combine them in exactly the same manner as they were broken down. Please note the color codes
given to these lists.
We first compare the element for each list and then combine them into another list in a sorted manner. We see
that 14 and 33 are in sorted positions. We compare 27 and 10 and in the target list of 2 values we put 10 first,
followed by 27. We change the order of 19 and 35 whereas 42 and 44 are placed sequentially.
In the next iteration of the combining phase, we compare lists of two data values, and merge them into a list of
found data values placing all in a sorted order.
After the final merging, the list should look like this
VENU-DRN
21
Algorithm
Merge sort keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is
only one element in the list, it is sorted. Then, merge sort combines the smaller sorted lists keeping the new list
sorted too.
procedure 2:
Steps to implement Merge Sort:
1) Divide the unsorted array into n partitions, each partition contains 1 element. Here the one element is
considered as sorted.
VENU-DRN
22
2) Repeatedly merge partitioned units to produce new sublists until there is only 1 sublist remaining. This will
be the sorted list at the end.
Merge sort is a fast, stable sorting routine with guaranteed O(n*log(n)) efficiency. When sorting arrays, merge
sort requires additional scratch space proportional to the size of the input array. Merge sort is relatively simple
to code and offers performance typically only slightly below that of quicksort.
PROGRAM
6.HEAP SORT
VENU-DRN
24
A sorting algorithm that works by first organizing the data to be sorted into a special type of
binary tree called a heap. The heap itself has, by definition, the largest value at the top of the tree,
so the heap sort algorithm must also reverse the order. It does this with the following steps:
1. Remove the topmost item (the largest) and replace it with the rightmost leaf. The topmost
item is stored in an array.
2. Re-establish the heap.
3. Repeat steps 1 and 2 until there are no more items left in the heap.
The sorted elements are now stored in an array.
A heap sort is especially efficient for data that is already stored in a binary tree. In most cases,
however, the quick sort algorithm is more efficient.
Algorithm:
An Example of Heapsort:
Given an array of 6 elements: 15, 19, 10, 7, 17, 16, sort it in ascending order using heap sort.
Steps:
Consider the values of the elements as priorities and build the heap tree.
Start deleteMin operations, storing each deleted element at the end of the heap array.
After performing step 2, the order of the elements will be opposite to the order in the heap tree.
Hence, if we want the elements to be sorted in ascending order, we need to build the heap tree
in descending order - the greatest element will have the highest priority.
Note that we use only one array , treating its parts differently:
when building the heap tree, part of the array will be considered as the heap,
and the rest part - the original array.
when sorting, part of the array will be the heap, and the rest part - the sorted array.
This will be indicated by colors: white for the original array, blue for the heap and red for the
sorted array
Here is the array: 15, 19, 10, 7, 17, 6
Building the heap tree
The array represented as a tree, complete but not ordered:
VENU-DRN
25
Start with the rightmost node at height 1 - the node at position 3 = Size/2.
It has one greater child and has to be percolated down:
The last node to be processed is array[1]. Its left child is the greater of the children.
The item at array[1] has to be percolated down to the left, swapped with array[2].
VENU-DRN
26
The children of array[2] are greater, and item 15 has to be moved down further, swapped with
array[5].
VENU-DRN
27
1.4. Percolate once more (10 is less that 15, so it cannot be inserted in the previous hole)
VENU-DRN
28
VENU-DRN
29
2.3. The element 10 is less than the children of the hole, and we percolate the hole down:
3. DeleteMax 16
3.1. Store 16 in a temporary place. A hole is created at the top
VENU-DRN
30
3.3. Percolate the hole down (7 cannot be inserted there - it is less than the children of the hole)
VENU-DRN
31
4.3. Store 10 in the hole (10 is greater than the children of the hole)
VENU-DRN
32
5.3. Store 7 in the hole (as the only remaining element in the heap
7 is the last element from the heap, so now the array is sorted
PROGRAM 1:
import java.util.*;
public class HeapSort
{
private static int N;
public static void sort(int arr[])
{
heapMethod(arr);
for (int i = N; i > 0; i--)
{
swap(arr,0, i);
N = N-1;
heap(arr, 0);
}
}
public static void heapMethod(int arr[])
{
N = arr.length-1;
for (int i = N/2; i >= 0; i--)
heap(arr, i);
}
public static void heap(int arr[], int i)
{
int left = 2*i ;
int right = 2*i + 1;
VENU-DRN
33
int max = i;
if (left <= N && arr[left] > arr[i])
max = left;
if (right <= N && arr[right] > arr[max])
max = right;
if (max != i)
{
swap(arr, i, max);
heap(arr, max);
}
}
public static void swap(int arr[], int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void main(String[] args)
{
Scanner in = new Scanner( System.in );
int n;
System.out.println("Enter the number of elements to be sorted:");
n = in.nextInt();
int arr[] = new int[ n ];
System.out.println("Enter "+ n +" integer elements");
for (int i = 0; i < n; i++)
arr[i] = in.nextInt();
sort(arr);
System.out.println("After sorting ");
for (int i = 0; i < n; i++)
System.out.println(arr[i]+" ");
System.out.println();
}
}
Program 2:
import java.util.Arrays;
public class HeapSort
{
int A[];
private void swap(int i, int j)
{
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
// To Max-Heapify a subtree rooted at node i which is
// an index in A[]. n -> size of heap
VENU-DRN
34
Notes:
Heap sort is an in-place algorithm.
Its typical implementation is not stable, but can be made stable.
Time Complexity: Time complexity of heapify is O(Logn). Time complexity of createAndBuildHeap() is O(n)
and overall time complexity of Heap Sort is O(nLogn).
VENU-DRN