Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
floyd_cycle_detection_algorithm.c File Reference

Implementation of Floyd's Cycle Detection algorithm. More...

#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
Include dependency graph for floyd_cycle_detection_algorithm.c:

Functions

uint32_t duplicateNumber (const uint32_t *in_arr, size_t n)
 for assert
 
static void test ()
 Self-test implementations.
 
int main ()
 Main function.
 

Detailed Description

Implementation of Floyd's Cycle Detection algorithm.

Given an array of integers containing n + 1 integers, where each integer is in the range [1, n] inclusive. If there is only one duplicate number in the input array, this algorithm returns the duplicate number in O(1) space and the time complexity is less than O(n^2) without modifying the original array, otherwise, it returns -1.

Author
Swastika Gupta

Function Documentation

◆ duplicateNumber()

uint32_t duplicateNumber ( const uint32_t *  in_arr,
size_t  n 
)

for assert

for uint32_t for IO operations

The main function implements the search algorithm

Template Parameters
Ttype of array
Parameters
in_arrthe input array
nsize of the array
Returns
the duplicate number

< variable tortoise is used for the longer jumps in the array

< variable hare is used for shorter jumps in the array

26{
27 if (n <= 1) { // to find duplicate in an array its size should be at least 2
28 return -1;
29 }
30 uint32_t tortoise = in_arr[0]; ///< variable tortoise is used for the longer
31 ///< jumps in the array
32 uint32_t hare = in_arr[0]; ///< variable hare is used for shorter jumps in the array
33 do { // loop to enter the cycle
34 tortoise = in_arr[tortoise]; // tortoise is moving by one step
35 hare = in_arr[in_arr[hare]]; // hare is moving by two steps
36 } while (tortoise != hare);
37 tortoise = in_arr[0];
38 while (tortoise != hare) { // loop to find the entry point of cycle
39 tortoise = in_arr[tortoise];
40 hare = in_arr[hare];
41 }
42 return tortoise;
43}

◆ main()

int main ( void  )

Main function.

Returns
0 on exit
65{
66 test(); // run self-test implementations
67 return 0;
68}
static void test()
Self-test implementations.
Definition floyd_cycle_detection_algorithm.c:49
Here is the call graph for this function:

◆ test()

static void test ( void  )
static

Self-test implementations.

Returns
void
50{
51 uint32_t arr[] = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}; // input array
52 size_t n = sizeof(arr) / sizeof(int);
53
54 printf("1st test... ");
55 uint32_t index = duplicateNumber(arr, n); // calling the duplicateNumber function to check which number occurs twice in the array
56 assert(index == 1); // the number which occurs twice is 1 or not
57 printf("passed\n");
58}
uint32_t duplicateNumber(const uint32_t *in_arr, size_t n)
for assert
Definition floyd_cycle_detection_algorithm.c:25
Here is the call graph for this function: