Program to swap first half with last half in an array

Write a program to swap first half with last half in an array.

Example,

Input
{ 1, 2, 3, 4, 5, 6, 7, 8 }
Output
{ 5, 6, 7, 8, 1, 2, 3, 4 }

Input
{ 12, 13, 14, 15, 16 }
Output
{ 15, 16, 14, 12, 13 }

Step

  1. Let arr be the input array.
  2. Let N be the length of arr.
  3. Set ptr1 = 0 ( Pointer to the first half of array ).
  4. Set ptr2 = ( N + 1 ) / 2 ( Pointer to the second half of the array ).
  5. Repeat the following steps while ptr2 < N ( or ptr1 < ( N + 1 ) / 2 )
    • Swap ( arr[ptr1] , arr[ptr2] )
    • ++ptr1, ++ptr2.
  6. Terminate the program

See the illustration of the above algorithm.

swap the first half with the second half of an array

Program to swap first half with last half in an array

#include <stdio.h>
#include <string.h>

void swap_first_second_half(int arr[], int n) {

	int temp, ptr1, ptr2;
	ptr1 = 0;				// pointer to first half
	ptr2 = (n + 1) / 2;		// pointer to second half

	while (ptr2 < n) {
		temp = arr[ptr1];
		arr[ptr1] = arr[ptr2];
		arr[ptr2] = temp;
		++ptr1;
		++ptr2;
	}

}

int main() {

	int arr[100];
	int n, i;

	printf("Enter size of array: ");
	scanf("%d", &n);

	printf("Enter array elements: \n");
	for (i = 0; i < n; ++i) {
		scanf("%d", &arr[i]);
	}

	printf("\nArray Before Swap: ");
	for (i = 0; i < n; ++i) {
		printf("%d ", arr[i]);
	}
	printf("\n\n");

	// calling swap function to swap first and second half of arr
	swap_first_second_half(arr, n);

	printf("Array After Swap: ");
	for (i = 0; i < n; ++i) {
		printf("%d ", arr[i]);
	}
	printf("\n\n");

}

Output

Enter size of array: 6
Enter array elements:
1 2 3 4 5 6

Array Before Swap: 1 2 3 4 5 6

Array After Swap: 4 5 6 1 2 3

Read

Leave a Comment