Last active
August 29, 2015 14:16
-
-
Save dakk/99cf800e72b17183a9e2 to your computer and use it in GitHub Desktop.
Remove an element from an array and re-compact it, with recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <malloc.h> | |
#define N 8 | |
/** Recursive delete like a pro | |
* where: 'ar' is the array, 'n' is the size, 'start' is 0 when | |
* called first time, 'irem' is the index of element to remove. | |
* @return the new size of the array (n-1) | |
*/ | |
int recdel (int *ar, int n, int start, int irem) | |
{ | |
if (start == n-1) | |
return start; | |
if (start >= (irem-1)) | |
ar[start] = ar[start+1]; | |
return recdel (ar,n,start+1,irem); | |
} | |
void print_ar (int *a, int n) | |
{ | |
for (int i=0;i<n;i++) printf ("%d ", a[i]); | |
printf ("\n\n"); | |
} | |
int main () | |
{ | |
int *ar = (int *) malloc (sizeof(int) * N); | |
// Inizializzo con numeri a caso | |
for (int i=0; i<N; i++) ar[i] = i+1; | |
print_ar (ar, N); | |
printf ("Elimino il 6' elemento\n"); | |
// Elimino il 6 elemento e ricompatto | |
int n = recdel (ar, N, 0, 6); | |
print_ar (ar, n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment