0% found this document useful (0 votes)
25 views2 pages

32-Block Swap Algorithm-03-06-2023

This Java code defines methods to left rotate an array by a given number of positions. It uses recursion to rotate parts of the array. The leftRotate method calls leftRotateRec to recursively rotate sections, and swap is used to exchange elements during rotation. The code is tested by left rotating an sample array by 2 positions and printing the result.

Uploaded by

Rahul Lokesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views2 pages

32-Block Swap Algorithm-03-06-2023

This Java code defines methods to left rotate an array by a given number of positions. It uses recursion to rotate parts of the array. The leftRotate method calls leftRotateRec to recursively rotate sections, and swap is used to exchange elements during rotation. The code is tested by left rotating an sample array by 2 positions and printing the result.

Uploaded by

Rahul Lokesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.util.

*;

class EthCode {

// It left rotates arr[] by d.


public static void leftRotate(int arr[], int d, int n) {
leftRotateRec(arr, 0, d, n);
}

public static void leftRotateRec(int arr[], int i, int d, int n) {


/* Return If number of elements to be rotated
is zero or equal to array size */
if (d == 0 || d == n)
return;

/*If number of elements to be rotated


is exactly half of array size */
if (n - d == d) {
swap(arr, i, n - d + i, d);
return;
}

/* If A is shorter*/
if (d < n - d) {
swap(arr, i, n - d + i, d);
leftRotateRec(arr, i, d, n - d);
} else /* If B is shorter*/ {
swap(arr, i, d, n - d);
leftRotateRec(arr, n - d + i, 2 * d - n, d); /*This is tricky*/
}
}

public static void printArray(int arr[], int size) {


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

/*This function swaps d elements


starting at index fi with d elements
starting at index si */
public static void swap(int arr[], int fi,
int si, int d) {
int i, temp;
for (i = 0; i < d; i++) {
temp = arr[fi + i];
arr[fi + i] = arr[si + i];
arr[si + i] = temp;
}
}

// Driver Code
public static void main(String[] args) {
int arr[] = {
1,
2,
3,
4,
5,
6,
7
};
leftRotate(arr, 2, 7);
printArray(arr, 7);
}
}

You might also like