Dsa Assignment 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

SORTING TECHNIQUES:

1. COMB SORT:
[Algorithm of Comb Sort]

STEP 1 START
STEP 2 Calculate the gap value if gap value==1 goto step 5 else goto step 3
STEP 3 Iterate over data set and compare each item with gap item then goto step 4.
STEP 4 Swap the element if require else goto step 2
STEP 5 Print the sorted array.
STEP 6 STOP

Code:

public static void combSort(int[] arr) {


int gap = arr.length;
boolean swapped = true;
while (gap != 1 || swapped == true) {
gap = getNextGap(gap);
swapped = false;
for (int i=0; i<arr.length-gap; i++) {
if (arr[i] > arr[i+gap]) {
int temp = arr[i];
arr[i] = arr[i+gap];
arr[i+gap] = temp;
swapped = true;
}} } }
static int getNextGap(int gap) {
gap = (gap*10)/13;
if (gap < 1)
return 1;
return gap; }

1
}

2. CYCLE SORT:
[Algorithm of Cycle Sort]
Step 1: Initialize a counter (cycle_start) to 0.
Step 2: Cycle through the array to find the item which is not in its correct position.
Step 3: Swap the item found with the item in its correct position.
Step 4: Increment cycle_start by 1.
Step 5: Repeat step 2, 3, and 4 until cycle_start is equal to the length of the array.
Step 6: The array is now sorted.

Code:

void sort(int a[], int n)


{
int writes = 0,start,element,pos,temp,i;

2
for (start = 0; start <= n - 2; start++) {
element = a[start];
pos = start;
for (i = start + 1; i < n; i++)
if (a[i] < element)
pos++;
if (pos == start)
continue;
while (element == a[pos])
pos += 1;
if (pos != start) {
temp = element;
element = a[pos];
a[pos] = temp;
writes++;
}
while (pos != start) {
pos = start;
for (i = start + 1; i < n; i++)
if (a[i] < element)
pos += 1;
while (element == a[pos])
pos += 1;
if (element != a[pos]) {
temp = element;
element = a[pos];
a[pos] = temp;
writes++;
}
}
}
}

3
3. COCKTAIL SORT:
[Algorithm of shell sort]

Step 1: Create a function create_sort


Step 2: Initialize two parameters array and len
Step 3: Declare swap, start, and end
Step 4: The element from the left side is compared to each neighboring element in the first
iteration, and if necessary, exchanged.
Step 5: The element from the right side which is recently is taken in the second iteration and
compared to each element to its right and switched if necessary
Step 6: Now the array is sorted

4
Step 7: Print the sorted array

Code:
for (int i = 0; i < n-1; i++)
{
bool swapped = false;
for (int j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(arr[j], arr[j+1]);
swapped = true;
}
}

if (swapped == false)
break;

swapped = false;
for (int j = n-i-1; j > i; j--)
{
if (arr[j] < arr[j-1])
{
swap(arr[j], arr[j-1]);
swapped = true;
}
}

if (swapped == false)
break;
}

5
4. PANCAKE SORT:
[Pancake sort algorithm]
Step 1: Start with the entire array of elements to be sorted.
Step 2: Find the maximum element in the array.
Step 3: Flip the array from the beginning up to the maximum element.
Step 4: Flip the array from the maximum element to the end.
Step 5: Repeat steps 2-4 until the array is sorted.

Code:

void flip(int arr[], int i)


{
int temp, start = 0;

6
while (start < i)
{
temp = arr[start];
arr[start] = arr[i];
arr[i] = temp;
start++;
i--;
}
}
// Returns index of the maximum element in arr[0..n-1]
int findMax(int arr[], int n)
{
int mi, i;
for (mi = 0, i = 0; i < n; ++i)
if (arr[i] > arr[mi])
mi = i;
return mi;
}
// The main function that sorts given array using flip operations
int pancakeSort(int *arr, int n)
{
for (int curr_size = n; curr_size > 1; --curr_size)
{
// Find index of the maximum element in arr[0..curr_size-1]
int mi = findMax(arr, curr_size);
if (mi != curr_size-1)
{
//To move at the end, first move maximum number to beginning
flip(arr, mi);
// Now move the maximum number to end by reversing current array
flip(arr, curr_size-1); } } }

7
5. TIM-SORT:
[Algorithm of Tim-sort]
Step 1: Divide the array into the number of blocks known as run.
Step 2: Consider the size of run, either 32 or 64.
Step 3: Sort the individual elements of every run one by one using insertion sort.
Step 4: Merge the sorted runs one by one using the merge function of merge sort.
Step 5: Double the size of merged sub-arrays after every iteration.

Code:

public static void timSort(int[] arr, int n)


{

8
int minRun = minRunLength(MIN_MERGE);

// Sort individual subarrays of size RUN


for (int i = 0; i < n; i += minRun)
{
insertionSort(arr, i,
Math.min((i + MIN_MERGE - 1), (n - 1)));
}

// Start merging from size


// RUN (or 32). It will
// merge to form size 64,
// then 128, 256 and so on
// ....
for (int size = minRun; size < n; size = 2 * size)
{

// Pick starting point


// of left sub array. We
// are going to merge
// arr[left..left+size-1]
// and arr[left+size, left+2*size-1]
// After every merge, we
// increase left by 2*size
for (int left = 0; left < n;
left += 2 * size)
{

// Find ending point of left sub array


// mid+1 is starting point of right sub
// array

9
int mid = left + size - 1;
int right = Math.min((left + 2 * size - 1),
(n - 1));
// Merge sub array arr[left.....mid] &
// arr[mid+1....right]
if(mid < right)
merge(arr, left, mid, right);
}
}
}

Divide the array into two parts:

Both sub arrays after sorting:

Now merge arrays to get final array as:

10
SEARCHING TECHNIQUES:
1) EXPONENETIAL SEARCH:
[Algorithm of Exponential Search in an Array]
STEP 1: Start by setting the range of indices to search as left = 0 and right = 1.
STEP 2: While the right index is less than the size of the array:
a) Calculate the mid index as mid = (left + right)/2
b) If the element at mid is the target element, return mid
c) If the element at mid is greater than the target element, set the right index to mid - 1
d) Else, set the left index to mid + 1
STEP 3: Set the left index to right and the right index to 2*right.
STEP 4: Repeat steps 2 and 3 until the target element is found or the right index is greater than or
equal to the size of the array.
STEP 5: If the target element is not found, return -1. Otherwise, return the index of the target
element.

Code:

public int exponentialSearch(int arr[], int x)


{
int n = arr.length;
// If x is present at first location itself if (arr[0] == x) return 0;
// Find range for binary search by
// repeated doubling
int i = 1;
while (i < n && arr[i] <= x)
i = i*2;
// Call binary search for the found range.
return Arrays.binarySearch(arr, i/2, Math.min(i, n), x);
}

11
2) FIBONACCI SEARCH:
[Algorithm of Fibonacci Search in an Array]
STEP 1: Find the smallest Fibonacci Number greater than or equal to n. Let this number be fibM
[m’th Fibonacci Number]. Let the two Fibonacci numbers preceding it be fibMm1 [(m-1)’th
Fibonacci Number] and fibMm2 [(m-2)’th Fibonacci Number].
STEP 2: While the array has elements to be inspected:
a. Compare x with the last element of the range covered by fibMm2.
b. If x matches, return index

12
c. Else If x is less than the element, move the three Fibonacci variables two Fibonacci
down, indicating elimination of approximately rear two-third of the remaining array.
d. Else x is greater than the element, move the three Fibonacci variables one Fibonacci
down. Reset offset to index. Together these indicate the elimination of approximately
front one-third of the remaining array
STEP 3: Since there might be a single element remaining for comparison, check if fibMm1 is 1.
If Yes, compare x with that remaining element. If match, return index.

Code:

public static int fibonacciSearch(int[] arr, int x)


{
int n = arr.length;

int fibMMm2 = 0; // (m-2)'th Fibonacci No.


int fibMMm1 = 1; // (m-1)'th Fibonacci No.
int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci
while (fibM < n)
{
fibMMm2 = fibMMm1;
fibMMm1 = fibM;
fibM = fibMMm2 + fibMMm1;
}
// Marks the eliminated range from front
int offset = -1;
while (fibM > 1)
{
// Check if fibMm2 is a valid location
int i = Math.min(offset+fibMMm2, n-1);
if (arr[i] < x)
{
fibM = fibMMm1;

13
fibMMm1 = fibMMm2;
fibMMm2 = fibM - fibMMm1;
offset = i;
}
else if (arr[i] > x)
{
fibM = fibMMm2;
fibMMm1 = fibMMm1 - fibMMm2;
fibMMm2 = fibM - fibMMm1;
}
else return i;
}

14
3) DEPTH-FIRST SEARCH:

[Algorithm of depth-first search]


STEP 1: SET STATUS = 1 (ready state) for each node in G
STEP 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
STEP 3: Repeat Steps 4 and 5 until STACK is empty
STEP 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)
STEP 5: Push on the stack all the neighbors of N that are in the ready state (whose STATUS = 1)
and set their STATUS = 2 (waiting state)
[END OF LOOP]
STEP 6: Exit

Code:

public void depthFirstSearch(Node rootNode){


//keep track of visited nodes
Set<Node> visitedNodes = new HashSet<>();
//create a stack for nodes to visit
Stack<Node> stack = new Stack<>();
//start from the root node
stack.push(rootNode);
//loop until all nodes are visited
while(!stack.isEmpty()){
Node currentNode = stack.pop();
//if the node is not visited
if(!visitedNodes.contains(currentNode)){
//visit the node
visitedNodes.add(currentNode);
System.out.println(currentNode.getName() + " visited");
//add all the unvisited adjacent nodes to the stack
for(Node adjacentNode : currentNode.getAdjacentNodes()){
if(!visitedNodes.contains(adjacentNode)){

15
stack.add(adjacentNode);
}
}

THE END

16

You might also like