I practice in c language, here is the exercise:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example :
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Here my attempt:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
static int r[2];
for(int i=0;i<numsSize;i++){
for(int j=0;j<numsSize;j++){
if(i!=j&&(nums[i]+nums[j])==target){
r[0]=i;
r[1]=j;
}
}
}
return r;
}
But Irecieve a wrong answer:
enter image description here
The function definition does not satisfies the requirement specified in the comment
Note: The returned array must be malloced, assume caller calls free()
Moreover the parameter
int* returnSize
is not used within your function definition.
It seems the function should be defined the following way as it is shown in the demonstration program below. I assume that any element in the source array can be present in the result array only one time.
#include <stdio.h>
#include <stdlib.h>
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int *twoSum( int *nums, int numsSize, int target, int *returnSize )
{
int *result = NULL;
*returnSize = 0;
for (int i = 0; i < numsSize; i++)
{
for (int j = i + 1; j < numsSize; j++)
{
if (nums[i] + nums[j] == target)
{
int unique = result == NULL;
if (!unique)
{
unique = 1;
for (int k = 1; unique && k < *returnSize; k += 2)
{
unique = nums[k] != nums[j];
}
}
if (unique)
{
int *tmp = realloc( result, ( *returnSize + 2 ) * sizeof( int ) );
if (tmp != NULL)
{
result = tmp;
result[*returnSize] = i;
result[*returnSize + 1] = j;
*returnSize += 2;
}
}
}
}
}
return result;
}
int main( void )
{
int a[] = { 2, 7, 11, 15 };
int target = 9;
int resultSize;
int *result = twoSum( a, sizeof( a ) / sizeof( *a ), target, &resultSize );
if (result)
{
for (int i = 0; i < resultSize; i += 2 )
{
printf( "%d, %d ", result[i], result[i + 1] );
}
putchar( '\n' );
}
free( result );
}
The program output is
0, 1
Though as for me then I would declare the function like
int *twoSum( const int *nums, size_t numsSize, int target, size_t *returnSize );
The brute force approach is very simple to this problem.
int* twoSum(int* arr, int n, int t, int* returnSize){
int *res=malloc(2*sizeof(int));
*returnSize=2;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if((arr[i]+arr[j])==t)
{
res[0]=i;
res[1]=j;
goto exit;
}
}
}
exit:
return res;
}
Related
i'm not good at english.
i declare array and two pointers.
the maxPtr pointer should have array arr's maximum number adress.
and minPtr pointer should have array arr's minimum number adress.
so i declare the function and this has two double-pointer to give maxPtr and minPtr proper adress.
but whenever i run this code, the program is not fully run.
it doesn't output the result( printf("%d",*maxPtr) ,printf("%d", *minPtr, printf("Hi");
this program is run at vscode in mac.
what make it error?
#include <stdio.h>
void MaxAndMin(int* str,int** max, int** min)
{
int i;
int maxnum=0,minnum=0;
for(i=0; i<5; i++)
{
if(maxnum< str[i])
{
maxnum =str[i];
*max = &str[i];
}
if(minnum > str[i])
{
minnum = str[i];
*min = &str[i];
}
}
}
int main(void)
{
int i,len;
int* maxPtr;
int* minPtr;
int arr[5]={};
for(i=0; i<5; i++)
{
printf("%d번째 정수입력 입니다.",i+1);
scanf("%d", &arr[i]);
}
MaxAndMin(arr,&maxPtr,&minPtr);
printf("%d",*maxPtr);
printf("%d",*minPtr);
printf("Hi");
return 0;
}
the result is
> Executing task: ./test <
1번째 정수입력 입니다.1
2번째 정수입력 입니다.2
3번째 정수입력 입니다.3
4번째 정수입력 입니다.4
5번째 정수입력 입니다.5
Terminal will be reused by tasks, press any key to close it.
For starters this initialization of an array
int arr[5]={};
is incorrect in C. You have to write
int arr[5]={ 0 };
Secondly using the magic number 5 within the function makes the function useless in general. You need to pass to the function the size of the array.
The initial value 0
int maxnum=0,minnum=0;
of these variables makes the function even more less useful. In general the array can contain either all elements positive or all elements negative.
And you need to flush the output buffer using for example the new line character '\n' in calls of printf.
The function can be declared and defined the following way as it is shown in the demonstration program below.
#include <stdio.h>
void MaxAndMin( const int a[], size_t n, int **max, int **min )
{
*max = ( int * )a;
*min = ( int * )a;
for ( size_t i = 1; i < n; i++ )
{
if ( **max < a[i] )
{
*max = ( int *)( a + i );
}
else if ( a[i] < **min )
{
*min = ( int * )( a + i );
}
}
}
int main( void )
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
int *maxPtr = NULL;
int *minPtr = NULL;
MaxAndMin( a, N, &maxPtr, &minPtr );
printf( "The maximum value is %d at position %tu\n",
*maxPtr, maxPtr - a );
printf( "The minimum value is %d at position %tu\n",
*minPtr, minPtr - a );
}
The program output is
The maximum value is 9 at position 9
The minimum value is 0 at position 0
Pay attention to that the first parameter of the function should have the qualifier const because passed arrays to the function are not changed within the function.
The main issue is that the minnum is set at zero, which would only work if array had a negative value.
Setting minimum = star[0] also would not work!!! Because in the case of str[0] having negative value, *min never gets changed.
Also, I recommend to always initialize all variables in the declaration, especially pointers (because they may theoretically cause accidental access to memory).
Full solution:
#include <stdio.h>
int MaxAndMin(int* str, int** max, int** min)
{
int i;
int maxnum = 0;
int minnum = str[0] + 1;
for(i=0; i<5; i++)
{
if(maxnum < str[i])
{
maxnum = str[i];
*max = &str[i];
}
if(minnum > str[i])
{
minnum = str[i];
*min = &str[i];
}
}
return 0;
}
int main(void)
{
int i = 0;
int len = 0;
int* maxPtr = NULL;
int* minPtr = NULL;
int arr[5]={};
for(i=0; i<5; i++)
{
printf("Enter number %d: ",i+1);
scanf("%d", &arr[i]);
}
MaxAndMin(arr, &maxPtr, &minPtr);
printf("%d",*maxPtr);
printf("%d",*minPtr);
printf("Hi");
return 0;
}
int *dynArr(int* arr, int n, int isEven) {
int count = 0;
int* t = (int*)calloc(n, sizeof(int));
assert(t);
if (isEven == 1) {
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
t[count++] = arr[i];
}
}
}
t = (int*)realloc(*t, count * sizeof(int));
return t;
}
void main() {
int a[] = { 1,8,3,6,11 };
int n = sizeof(a) / sizeof(int);
int isEven = 1;
int* arr = dynArr(a, n, isEven);
for (int i = 0; i < n; i++) {
printf("%d", arr[i]);
}
}
The problem is when I'm returning the array I don't get any output, When I'm debugging I get this error: "Unhandled exception at 0x7A08B54D (ucrtbased.dll) in homelab8.exe: 0xC0000005: Access violation reading location 0x00000004."
Someone have an idea how do I fix this?
First of all, you are passing a bad parameter to realloc. This would easily have been caught had you been using your compiler's warnings.
The other major issue is that you are accessing n elements of the array pointed by arr, but it doesn't have n elements.
Since you have two values to return, you will need to return through arguments (or return a struct).
// Returns 0 on success.
// Returns -1 and sets errno on error.
int filter_even_or_odd(
int **filtered_arr_ptr, // The address of a variable that accepts output.
size_t *filtered_n_ptr, // The address of a variable that accepts output.
int *arr,
size_t n,
int keep_even // Keep even or keep odd?
) {
size_t filtered_n = 0;
int *filtered_arr = malloc( sizeof(int) * n );
if (!filtered_arr)
return -1;
int to_keep = keep_even ? 0 : 1;
for ( size_t i = 0; i < n; i++ ) {
if ( arr[i] % 2 == to_keep ) {
filtered_arr[ filtered_n++ ] = arr[i];
}
}
int *tmp = realloc( filtered_arr, sizeof(int) * filtered_n );
if (tmp)
filtered_arr = tmp;
*filtered_arr_ptr = filtered_arr;
*filtered_n_ptr = filtered_n;
return 0;
}
What is wrong with this code and where is the problem?
I ran this code many times but it's showing that the code is running but I am not getting any output.
Can you tell me where is the mistake?
#include <stdio.h>
int print_arr(int *arr, int n)
{ for(int i=0; i<=n; i++)
{
printf("%d ",arr[i]);
}
return 0;
}
int insert_ele(int *arr_a, int *arr_b, int n, int Key)
{
int i,j;
for(i=0, j=0; i<n; i++, j++)
{
if(arr_a[i]>Key)
{
arr_b[j] = Key;
arr_b[j+1] = arr_a[i];
j++;
}
else
{
arr_b[j] = arr_a[i];
}
}
return 0;
}
int main()
{
//code
int arr_a[] = {12, 16, 20, 40, 50, 70};
int arr_b[10];
int Key = 26;
int n = sizeof(arr_a)/sizeof(arr_a[0]);
int indx = insert_ele(arr_a, arr_b, n, Key);
print_arr(arr, n);
return 0;
}
For starters there is a typo in this statement
print_arr(arr, n);
It seems you mean
print_arr( arr_b, n + 1 );
The return type int of the function print_arr does not make a sense and is useless.
The first parameter of the function should have the qualifier const because the passed array is not being changed within the function.
The second parameter should have the type size_t.
This for loop
for(int i=0; i<=n; i++)
can invoke undefined behavior if the user of the function will pass the number of elements in the array in the second parameter n because in this case there will be an attempt to access memory beyond the array.
Again the return type int of the function insert_ele does not make a sense and is useless.
The first parameter should have the qualifier const because the source array is not being changed within the function. The parameter n should have the type size_t.
The function has a logical error.
Let's assume that the value of the variable Key is less than values of all elements of the array arr_a.
In this case the index j will be incremented twice and as a result you will have
b[0] = Key; b[2] = Key; b[4] = Key; and so on.
The logic of the function will be much clear if to split the for loop in two for loops.
The program can look the following way.
#include <stdio.h>
size_t insert_ele( const int *a, size_t n, int *b, int key )
{
size_t i = 0;
for ( ; i < n && !( key < a[i] ); i++ )
{
b[i] = a[i];
}
b[i] = key;
for ( ; i < n; i++ )
{
b[i+1] = a[i];
}
return i;
}
FILE * print_arr( const int *a, size_t n, FILE *fp )
{
for ( size_t i = 0; i < n; i++)
{
fprintf( fp, "%d ", a[i] );
}
return fp;
}
int main(void)
{
int a[] = { 12, 16, 20, 40, 50, 70 };
const size_t N = sizeof( a ) / sizeof( *a );
int b[10];
int key = 26;
size_t m = insert_ele( a, N, b, key );
fputc( '\n', print_arr( b, m, stdout ) );
return 0;
}
The program output is
12 16 20 26 40 50
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
#include<stdio.h>
int* twoSum(int* nums, int numsSize, int target);
int main(){
int*array;
int arraySize;
scanf("%d",&arraySize);
for (int i=0;i<arraySize;i++){
scanf("%d",&array[i]);
}
int target;
scanf("%d",&target);
int* positions=twoSum(array, arraySize, target);
printf("The positions are: %p",positions);
return 0;
}
int* twoSum(int* nums, int numsSize, int target){
int *returnSize = NULL;
for(int i=0,sum=0;i<numsSize;i++){
for(int j=0;j<numsSize;j++){
sum =sum+nums[i]+nums[j];
if(sum==target){
returnSize[0]=nums[i];
returnSize[1]=nums[j];
}
else
returnSize[0]= -1;
returnSize[1]= -1;
}
}
return returnSize;
}
The error I am getting makes reference to a line that is empty in my code. Please help
there are mistakes in this code.First you should allocate memory for int*array; after taking int arraySize; as input , you can do it like this
array = malloc(sizeof(int) * arraySize);
then here %p is not appropriate , instead use %d. Take look here for more information about %p %p format specifier and also since you want to print 2 positions you need to call two arguments in printf like this printf("The positions are: %d %d", positions[0], positions[1]);
In your twoSum function , you need to allocate memory for int* returnSize ; like this returnSize = malloc(sizeof(int) * 2);
and here you are not returning positions of found elements , you are returning elements themselfs.
if(sum==target){
returnSize[0]=nums[i];
returnSize[1]=nums[j];
}
also you need to add return in this if-statement other wise , you will traverse array completely and returnSize elements will become -1 again(unless answer is too last element of array)
so this if should be like this:
if (sum == target) {
returnSize[0] = i;//num[i] is not position. it is element of array
returnSize[1] = j;//num[j] is not position .it is element of array
return returnSize;//otherwise it will traverse array compeltely and they -1 again
}
also only if you code one line for if,else,while,for,... (conditional statements) ,you can avoid using braces ,otherwise only one line of your code will executed ,if that condition become true ,so you have to add a block for this else:
else
{
returnSize[0] = -1;
returnSize[1] = -1;
}//coding more than one line so your else should be in a block
and also here sum=sum+num[i]+num[j]; is wrong you should change this to sum=num[i]+num[j]; because you only want to check sum of two current number ,or better way don't use sum at all only check equality of target with num[i]+num[j]
here is complete code:
int* twoSum(int* nums, int numsSize, int target);
int main() {
int* array;
int arraySize;
scanf("%d", &arraySize);
array = malloc(sizeof(int) * arraySize);//allocate memory for array
for (int i = 0; i < arraySize; i++) {
scanf("%d", &array[i]);
}
int target;
scanf("%d", &target);
int* positions = twoSum(array, arraySize, target);
printf("The positions are: %d %d", positions[0], positions[1]);//%p is for not for content of array
return 0;
}
int* twoSum(int* nums, int numsSize, int target) {
int* returnSize ;
returnSize = malloc(sizeof(int) * 2);
for (int i = 0; i < numsSize; i++) {
for (int j = 0; j < numsSize; j++) {
if (nums[i] + nums[j] == target) {
returnSize[0] = i;//num[i] is not position. it is element of array
returnSize[1] = j;//num[j] is not position .it is element of array
return returnSize;//otherwise it will traverse array compeltely and they -1 again
}
else
{
returnSize[0] = -1;
returnSize[1] = -1;
}//coding more than one line so your else should be in a block
}
}
return returnSize;
}
There is some mistakes in your code:
memory allocation
You declare pointers on int to store data to process and result, but you do not allocate memory: malloc is for Memory ALLOCation:
array = malloc(sizeof *array * arraySize);
and
int *returnSize = malloc(sizeof *returnSize * 2);
Sum calculation logic
sum value
In twoSum function, the sum variable is getting bigger and bigger: sum =sum+nums[i]+nums[j];
Instead, a simple if (target == nums[i] + nums[j]) will perform the test you wanted.
sum test
In your code, each time sum is not equal to target, you reset returnSize[0] to -1
You do not have to have an else clause: you can initialize the returnSize before the for loop.
missing {...}
Look at your first code: for any value of sum and target, returnSize[1] is set to -1 because you've forgotten to put accolades after the else (but, as written before, you do not even need an else)
gcc can warn you about such issue (-Wmisleading-indentation, or better -Wall)
for(int j=0;j<numsSize;j++){
sum =sum+nums[i]+nums[j];
if(sum==target){
returnSize[0]=nums[i];
returnSize[1]=nums[j];
}
else
returnSize[0]= -1;
returnSize[1]= -1;
}
Considering this, you can write a code that do what you wanted.
Be careful, you should test the scanf and malloc return values too...
#include <stdio.h>
#include <stdlib.h>
int *twoSum(int *nums, int numsSize, int target);
int main()
{
int *array;
int arraySize;
// TODO: test that scanf returned 1
scanf("%d", &arraySize);
// TODO: test that arraysize is at least 2
/* allocate array to store the numbers*/
array = malloc(sizeof *array * arraySize);
for (int i = 0; i < arraySize; i++) {
// TODO: test that scanf returned 1
scanf("%d", &array[i]);
}
int target;
// TODO: test that scanf returned 1
scanf("%d", &target);
int *positions = twoSum(array, arraySize, target);
printf("The positions are: %d(%d) %d(%d)\n", positions[0], array[positions[0]], positions[1], array[positions[1]]);
/* memory has been allocated? free it */
free(positions)
free(array)
return 0;
}
int *twoSum(int *nums, int numsSize, int target)
{
int *returnSize = malloc(sizeof *returnSize * 2);
returnSize[0] = returnSize[1] = -1;
for (int i = 0; i < numsSize; i++) {
for (int j = 0; j < numsSize; j++) {
if (target ==nums[i] + nums[j] ) {
returnSize[0] = i;
returnSize[1] = j;
return returnSize;
}
}
}
return returnSize;
}
Here your code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int* twoSum(int* nums, int numsSize, int target);
void print_pos(int * arr, int i) {
printf("test %d\n", i);
if (arr != NULL) {
printf("position 1 = %d, position 2 = %d\n", arr[0], arr[1]);
} else
printf("Not found\n");
}
int main(){
int array[5] = {5, 6, 2 ,1 ,3} ;
int target1 = 11, target2 = 9, target3 = 15;
int * positions1=twoSum(array, 5, target1);
int * positions2=twoSum(array, 5, target2);
int * positions3=twoSum(array, 5, target3);
print_pos(positions1, 1);
print_pos(positions2, 2);
print_pos(positions3, 3);
return 0;
}
int* twoSum(int* nums, int numsSize, int target){
int *return_arr = malloc(sizeof(int) * 2);
bool found = false;
for(int i=0;i<numsSize;i++){
for(int j=0;j<numsSize;j++){
if((nums[i]+nums[j])==target){
return_arr[0]= i;
return_arr[1]= j;
found = true;
}
}
}
if (found)
return return_arr;
else {
free(return_arr);
return NULL;
}
}
I encountered the following question in an interview.
Complete this function to return a reversed array without modifying the function signature or the original array. Note that static data types should not be used here at all.
Assume the arrayLength is a power of 2. i.e 2^n. -> I think this is the trick here.
int* reverse(int *array, int arrayLength){
}
Please help.
Note that I could not really think of a solution to the problem. The interviewer hinted at using 2^n for the puspose, but i could not really think of the solution.
How about this:
int* reverse(int *array, int arrayLength){
if (arrayLength==1) {
int* out=(int*)malloc(sizeof(int));
out[0] = array[0];
return out;
}
int* left = reverse(array+arrayLength/2, arrayLength-arrayLength/2);
int* right = reverse(array,arrayLength/2);
int* out = (int*)realloc(left, sizeof(int)*arrayLength);
memcpy(out+arrayLength/2, right, sizeof(int)*(arrayLength/2));
free(right);
return out;
}
Agree with OP the the hint is "2^n". As with many recursive functions: divide and conquer.
This routine first deals with errant paramters and the simple lengths. Next, divide the length in half and reverse each half. Form the result by concatenating the reversed left and right sub-arrays. First, right, then left.
Usual clean-up follows
#include <string.h>
#include <stdlib.h>
int* reverse(int *array, int arrayLength) {
// Check parameters
if (array == NULL || arrayLength < 0) {
; // TBD HandleBadParameters();
}
// Allocate space for result, not much to do if length <= 1
int *y = malloc(arrayLength * sizeof *y);
if (y == NULL) {
; // TBD HandleOOM();
}
if (arrayLength <= 1) {
memcpy(y, array, arrayLength * sizeof *y);
return y;
}
// Find reverse of the two halves
int halflength = arrayLength / 2;
int *left = reverse(array, halflength);
int *right = reverse(&array[halflength], halflength);
// Append them to the result - in reverse order
memcpy(y, right, halflength * sizeof *y);
memcpy(&y[halflength], left, halflength * sizeof *y);
// Clean-up and return
free(right);
free(left);
return y;
}
int* reverse(int *array, int arrayLength){
if(arrayLength == 0) return array;
int* ret = (int*)malloc(arrayLength*sizeof(int));
for(int i=0;i<arrayLength;i++) ret[i] = array[arrayLength-1-i];
return reverse(ret, 0); // technically recursive
}
Here it is (and works):
int *reverse(int *array, int arrayLength)
{
if (arrayLength > 1) {
int i, n = arrayLength >> 1;
int *m = calloc(n, sizeof(int));
memcpy(m, array, n*sizeof(int));
memcpy(array, array + n, n*sizeof(int));
memcpy(array + n, m, n*sizeof(int));
free(m);
reverse(array, n);
reverse(array+n, n);
} /* for */
return array;
} /* reverse */
it can be done without temporary storage, but you have to iterate a little.
int *reverse(int *a, int al)
{
if (al > 1) {
int i, a1 = al >> 1;
for (i = 0; i < a1; i++) {
int temp = a[i];
a[i] = a[i + a1];
a[i + a1] = temp;
} /* for */
reverse(a, a1);
reverse(a+a1, a1);
} /* for */
return a;
} /* reverse */
but, it would be nicer just to exchange from the boundaries to the middle and do it completely iterative.
int *reverse(int *array, int arrayLength)
{
int a, b;
for (a = 0, b = arrayLength-1; a < b; a++, b--) {
int temp = array[a];
array[a] = array[b];
array[b] = temp;
} /* for */
return array;
} /* reverse */
And just for the ones who asked for a non selfmodifying array, this all-inefficient form:
int *reverse(int *array, int arrayLength)
{
int *a1, *a2;
int *res;
if (arrayLength > 1) {
int l = arrayLength >> 1;
a1 = reverse(array, l);
a2 = reverse(array + l, l);
res = calloc(arrayLength, sizeof(int));
memcpy(res, a2, l*sizeof(int));
memcpy(res+l, a1, l*sizeof(int));
free(a1);
free(a2);
} else {
/* we return always memory alloc'd with malloc() so we have to do this. */
res = malloc(sizeof(int));
*res = array[0];
} /* if */
return res;
} /* reverse */
Well, here's one sneaky way, and it doesn't care what length the array is. Note: I'm assuming you can't introduce a new function, it has to be done all within the existing function
if the length is postive, it allocates memory and makes a copy, then calls reverse again with a negative length and the copy, then if the function is called with a negative length, it reverses the first and last inplace, then recursively calls by moving to the next in the array and shrinks the length till there is nothing left to reverse and then the recursive function unwinds
int* reverse(int *array, int arrayLength){
int* result;
if(arrayLength > 0)
{
result =(int*) malloc((sizeof(int)*arrayLength));
memcpy(result, array, sizeof(int)*arrayLength);
reverse(result, -arrayLength);
return result;
}
else if(arrayLength < -1)
{
int end = (-arrayLength)-1;
int temp = array[end];
array[end] = array[0];
array[0] = temp;
return reverse(array+1, arrayLength+2);
}
return array;
}
Considering that arrayLength is always a power of 2. we will apply the function to the two parts of the array then concat them in the reverse way.
Finaly if the array has only one element, we simply return other array with the same element.
int* reverse(int *array, int arrayLength){
int * newArray = NULL;
if(arrayLength == 1){
newArray = (int *)malloc(sizeof(int));
*newArray = array[0];
} else if(arrayLength == 2){
newArray = (int *)malloc(2 * sizeof(int));
newArray[0] = array[1];
newArray[1] = array[0];
} else {
// apply to first half
int * first = reverse(array, arrayLength / 2);
// apply to second half
int * second = reverse(array + arrayLength / 2, arrayLength / 2);
// allocate space
newArray = (int *) malloc(arrayLength * sizeof(int));
// copy parts in reverse way
memcpy(newArray, second, arrayLength / 2 * sizeof(int));
memcpy(newArray + arrayLength / 2, first, arrayLength / 2 * sizeof(int));
// free allocated space for parts
free(first);
free(second);
}
return newArray;
}
I'll give it a shot.
Knowing that the array is of length 2^n means that it can be safely halved. We call the function recursively on each half until length is 2. At this point we swap the two integers. Think { 2,1,4,3,6,5,8,7 }. When we come back from that, each half is then merged opposite of where it came from ( { 4,3,2,1,8,7,6,5} ). Rinse and repeat.
#include <stdio.h>
#include <stdlib.h>
int * reverse( int* arr, int length )
{
if ( length == 1 )
{
int *result = malloc( sizeof( arr[0] ) );
result[0] = arr[0];
return result;
}
int * result = 0;
if ( length == 2 )
{
result = malloc( sizeof( arr[0] ) * 2 );
result[0] = arr[1];
result[1] = arr[0];
}
else
{
int half_length = length / 2;
// named correctly
int * right = reverse( arr, half_length );
int * left = reverse( arr + half_length, half_length );
result = malloc( sizeof( arr[0] ) * length );
for ( int i = 0; i < half_length; ++i )
{
result[i] = left[i];
result[ i + half_length ] = right[i];
}
free( right );
free( left );
}
return result;
}
int main( void )
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int length = 8;
int *reversed = reverse( arr, length );
for ( int i = 0; i < length; ++i )
{
printf( "%d %d\n", arr[i], reversed[i] );
}
free( reversed );
return 0;
}
for all integer arrays with more than 2 elements.
The basic idea is to swap elements from both ends untill the number of elements remaining is 1.
int* reverse_array(int* array, int arrayLength)
{
if(arrayLength <2)
{
return NULL;
}
else
{
int *array1 = NULL;
int *array2 = NULL;
array1 = malloc(arrayLength*sizeof(int));
memcpy(array1,array,arrayLength*sizeof(int));
/*swap the start and end*/
swap(array1,(array1+arrayLength-1));
/* swap the next pair */
array2 = reverse_array(array1+1,arrayLength-2);
memcpy(array1+1,array2,(arrayLength-2)*sizeof(int));
if(array2!= NULL)
{
free(array2);
}
return array1;
}
}