forked from Code-Recursion/DataStructuresAndAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinear_search.c
79 lines (65 loc) · 1.5 KB
/
linear_search.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// improved Linear Search
// 1 - transposition key is moved one position left ,
// decrease one step from next search
// 2 - Move to Head/Tail, key is swapped with tail/head,
// optimize search to O[1] for next searches
#include <stdio.h>
#include <stdlib.h>
struct Array
{
int A[100];
int size;
int length;
};
void Display(struct Array arr)
{
printf("\nElement in array are : ");
for (int i = 0; i < arr.length; i++)
printf("%d ", arr.A[i]);
}
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int LinearSearchMoveToHead(struct Array *arr, int key)
{
for (int i = 0; i < arr->length; i++)
{
if (key == arr->A[i])
{
swap(&arr->A[0], &arr->A[i]);
return i;
}
}
return -1;
}
// int LinearSearchTransposition(struct Array *arr, int key)
// {
// for (int i = 0; i < arr->length; i++)
// {
// if (key == arr->A[i])
// {
// swap(&arr->A[i], &arr->A[i - 1]);
// return i;
// }
// }
// return -1;
// }
int main()
{
struct Array arr = {{2, 3, 4, 5, 6}, 10, 5};
Display(arr);
// printf("\nElement found at index : %d", LinearSearchTransposition(&arr, 4));
printf("\nElement found at index : %d", LinearSearchMoveToHead(&arr, 4));
Display(arr);
return 0;
}
// Output :
// Element in array are : 2 3 4 5 6
// Element found at index : 2
// Element in array are : 4 3 2 5 6
// Analysis :
// worst : O[n]
// Best : O[1]