Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Block Swap Algorithm

Uploaded by

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

Block Swap Algorithm

Uploaded by

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

~Block swap algorithm~

Also known as array rotation.

Operates by dividing the array into two blocks and then swapping the elements
between these blocks in a specific manner.

TIME COMPLEXITY = O(n)

The rotation is by 'd' elements.


The two blocks are 'd' and 'n - d'
Base condition -> d == 0 or d == n

APPLICATION:
-> Data shifting: To shift data cyclically such as elements in buffer array or
shift cyclic operations.

-> Memory Management: Can be used to optimize in place array rotation without using
extra memory.

-> Circular buffers: manage data movement in cyclic buffers.

CODE:
class BlockSwap{
static int[] swap(int[] arr, int k, int n){
if(k == 0 | k == n){
return arr;
}
if(k > n){
k %= n;
}
int[] result = new int[n];
for(int i = 0; i < n; i++){
result[i] = arr[(i + k)%n];
//for right rotate (n - k + 1)
}
return result;
}

public static void printArray(int[] arr) {


for (int element : arr) {
System.out.print(element + " ");
}
System.out.println();
}

public static void main(String[] args){


int[] array = {1, 5, 3, 2, 8, 9};
int a = 3;
int b = 5;
printArray(swap(array, a, b));
}

You might also like