Sie sind auf Seite 1von 35

1

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];

System.out.println("Enter " + n + " integers");

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


array[i] = in.nextInt();

System.out.println("Enter value to find");


search = in.nextInt();

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


{
if (array[i] == search) /* Searching element is present */
{

VENU-DRN
2

System.out.println(search + " is present at location " + ( i+ 1));


break;
}
}
if (i == n) /* Searching element is absent */
System.out.println(search + " is not present in array.");
}
}

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.

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.

First, we shall determine half of the array by using this formula


mid = low + (high - low) / 2
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.

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.

Hence, we calculate the mid again. This time it is 5.


mid = low + (high - low) / 2
mid=(5+6)/2=>5

We compare the value stored at location 5 with our target value. We find that it is a match.

We conclude that the target value 31 is stored at location 5.


Binary search halves the searchable items and thus reduces the count of comparisons to be made to very less
numbers.

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();

System.out.println("Enter value to find");


search = in.nextInt();

first = 0;
last = n - 1;
middle = (first + last)/2;

while( first <= last )


{
VENU-DRN
5

if ( array[middle] < search )


first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}

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.

How Selection Sort Works?


Consider the following depicted array as an example.

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.

Following is a pictorial depiction of the entire sorting process

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

swap list[min] and list[i]


end if
end for
end procedure

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.

How Insertion Sort Works?

We take an unsorted array for our example.

Insertion sort compares the first two elements.

It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.

Insertion sort moves ahead and compares 33 with 27.

And finds that 33 is not in the correct position.

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

These values are not in a sorted order.

So we swap them.

However, swapping makes 27 and 10 unsorted.

Hence, we swap them too.

Again we find 14 and 10 in an unsorted order.

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.

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
VENU-DRN
11

Step 5 Insert the value


Step 6 Repeat until list is sorted
Pseudocode

procedure insertionSort( A : array of items )


int holePosition
int valueToInsert
for i = 1 to length(A) inclusive do:
/* select value to be inserted */
valueToInsert = A[i]
holePosition = i
/*locate hole position for the element to be inserted */
while holePosition > 0 and A[holePosition-1] > valueToInsert do:
A[holePosition] = A[holePosition-1]
holePosition = holePosition -1
end while
/* insert the number at hole position */
A[holePosition] = valueToInsert
end for
end procedure

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;
}
}

public static void main(String a[]){


int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Insertion Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();

insertionSort(arr1);//sorting array using insertion sort

System.out.println("After Insertion Sort");


for(int i:arr1){
System.out.print(i+" ");
VENU-DRN
12

}
}
}

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.

How Bubble Sort Works?


We take an unsorted array for our example. Bubble sort takes (n2) time so we're keeping it short and precise.

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.

The new array should look like this

Next we compare 33 and 35. We find that both are in already sorted positions.

VENU-DRN
13

Then we move to the next two values, 35 and 10.

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.

Now we should look into some practical aspects of bubble sort.

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)

for all elements of list


if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for

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.

Pseudocode of BubbleSort algorithm can be written as follows

procedure bubbleSort( list : array of items )


loop = list.count;
for i = 0 to loop-1 do:
swapped = false
for j = 0 to loop-1 do:
/* compare the adjacent elements */
if list[j] > list[j+1] then
/* swap them */
swap( list[j], list[j+1] )
swapped = true
end if

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};

System.out.println("Array Before Bubble Sort");


for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
System.out.println();

bubbleSort(arr);//sorting array elements using bubble sort

System.out.println("Array After Bubble Sort");


for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
}
}

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

Partition algorithm in detail

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.

Example. Sort {1, 12, 5, 26, 7, 14, 3, 7, 2} using quicksort.

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

public class MyQuickSort


{
private int array[];
private int length;
public void sort(int[] inputArr)
{
if (inputArr == null || inputArr.length == 0)
{
return;
}
this.array = inputArr;
length = inputArr.length;
quickSort(0, length - 1);
}
private void quickSort(int lowerIndex, int higherIndex)
{

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:

How Merge Sort Works?


To understand merge sort, we take an unsorted array as the following

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

Now we should learn some programming aspects of merge sorting.

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.

Step 1 if it is only one element in the list it is already sorted, return.


Step 2 divide the list recursively into two halves until it can no more be divided.
Step 3 merge the smaller lists into new list in sorted order.
Pseudocode
We shall now see the pseudocodes for merge sort functions. As our algorithms point out two main functions
divide & merge.Merge sort works with recursion and we shall see our implementation in the same way.

procedure mergesort( var a as array )


if ( n == 1 ) return a
var l1 as array = a[0] ... a[n/2]
var l2 as array = a[n/2+1] ... a[n]
l1 = mergesort( l1 )
l2 = mergesort( l2 )
return merge( l1, l2 )
end procedure
procedure merge( var a as array, var b as array )
var c as array
while ( a and b have elements )
if ( a[0] > b[0] )
add b[0] to the end of c
remove b[0] from b
else
add a[0] to the end of c
remove a[0] from a
end if
end while
while ( a has elements )
add a[0] to the end of c
remove a[0] from a
end while
while ( b has elements )
add b[0] to the end of c
remove b[0] from b
end while
return c
end procedure

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

public class MyMergeSort


{
private int array[];
private int tempMergArr[];
private int length;
public static void main(String a[])
{
int[] inputArr = {45,23,11,89,77,98,4,28,65,43};
MyMergeSort mms = new MyMergeSort();
mms.sort(inputArr);
for(int i:inputArr){
System.out.print(i);
System.out.print(" ");
}
}
VENU-DRN
23

public void sort(int inputArr[])


{
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
}
private void doMergeSort(int lowerIndex, int higherIndex) {

if (lowerIndex < higherIndex) {


int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
// Below step sorts the left side of the array
doMergeSort(lowerIndex, middle);
// Below step sorts the right side of the array
doMergeSort(middle + 1, higherIndex);
// Now merge both sides
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex)
{
for (int i = lowerIndex; i <= higherIndex; i++) {
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex) {
if (tempMergArr[i] <= tempMergArr[j]) {
array[k] = tempMergArr[i];
i++;
}
else
{
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle) {
array[k] = tempMergArr[i];
k++;
i++;
}
}
}

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:

Step 1 Create a new node at the end of heap.


Step 2 Assign new value to the node.
Step 3 Compare the value of this child node with its parent.
Step 4 If value of parent is less than child, then swap them.
Step 5 Repeat step 3 & 4 until Heap property holds.

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:

After processing array[3] the situation is:

Next comes array[2]. Its children are smaller, so no percolation is needed.

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

As a result the situation is:

The children of array[2] are greater, and item 15 has to be moved down further, swapped with
array[5].

Now the tree is ordered, and the binary heap is built.


Sorting - performing deleteMax operations:
1. Delete the top element 19.
1.1. Store 19 in a temporary place. A hole is created at the top

VENU-DRN
27

1.2. Swap 19 with the last element of the heap.


As 10 will be adjusted in the heap, its cell will no longer be a part of the heap.
Instead it becomes a cell from the sorted array

1.3. Percolate down the hole

1.4. Percolate once more (10 is less that 15, so it cannot be inserted in the previous hole)

VENU-DRN
28

Now 10 can be inserted in the hole

2. DeleteMax the top element 17


2.1. Store 17 in a temporary place. A hole is created at the top

2.2. Swap 17 with the last element of the heap.


As 10 will be adjusted in the heap, its cell will no longer be a part of the heap.
Instead it becomes a cell from the sorted array

VENU-DRN
29

2.3. The element 10 is less than the children of the hole, and we percolate the hole down:

2.4. Insert 10 in the hole

3. DeleteMax 16
3.1. Store 16 in a temporary place. A hole is created at the top

VENU-DRN
30

3.2. Swap 16 with the last element of the heap.


As 7 will be adjusted in the heap, its cell will no longer be a part of the heap.
Instead it becomes a cell from the sorted array

3.3. Percolate the hole down (7 cannot be inserted there - it is less than the children of the hole)

3.4. Insert 7 in the hole

4. DeleteMax the top element 15


4.1. Store 15 in a temporary location. A hole is created.

VENU-DRN
31

4.2. Swap 15 with the last element of the heap.


As 10 will be adjusted in the heap, its cell will no longer be a part of the heap.
Instead it becomes a position from the sorted array

4.3. Store 10 in the hole (10 is greater than the children of the hole)

5. DeleteMax the top element 10.


5.1. Remove 10 from the heap and store it into a temporary location.

5.2. Swap 10 with the last element of the heap.


As 7 will be adjusted in the heap, its cell will no longer be a part of the heap. Instead it becomes
a cell from the sorted array

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

void maxHeapify(int A[],int n, int i)


{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && A[l] > A[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && A[r] > A[largest])
largest = r;
// If largest is not root
if (largest != i)
{
swap(i,largest);
// Recursively heapify the affected sub-tree
maxHeapify(A,n,largest);
}
}
// Build-Max-Heap (rearrange array)
//Converting array A to Max-Heap
public void BuildMaxHeap(int A[])
{
int n = A.length;
// one by one checking all root nodes
//and calling Heapify function
//if they does not satisfy heap property
for (int i = n / 2 - 1; i >= 0; i--)
maxHeapify(A,n,i);
}
// main function to do Heap Sort
public void heapSort(int arr[])
{
this.A=arr;
int n = A.length;
BuildMaxHeap(A);
// One by one extract an element from heap
//and get the sorted array
for (int i=n-1; i>=0; i--)
{
// Move top root element to end element
swap(0,i);
// call max heapify on the reduced heap
maxHeapify(arr, i, 0);
}
}
// Driver program
public static void main(String args[])
{
VENU-DRN
35

int arr[] = {6,5,3,1,8,7,2,4};


//print unsorted array using Arrays.toString()
System.out.print("Unsorted array: ");
System.out.println(Arrays.toString(arr));
HeapSort ob = new HeapSort();
ob.heapSort(arr);
System.out.print("Sorted array: ");
//print sorted array
System.out.println(Arrays.toString(arr));
}
}

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