Skip to content

Commit 5decd7e

Browse files
authored
Create Algosi_LV1
1 parent 9dd512e commit 5decd7e

File tree

1 file changed

+131
-0
lines changed

1 file changed

+131
-0
lines changed

Algosi_LV1

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
#include <stdio.h>
2+
#include <time.h>
3+
#include <stdlib.h>
4+
5+
void gen_arr(float V[], int n, float dg, float gg );
6+
int sekv_pret( float V[], int n, float x );
7+
void sort( float V[], int n );
8+
void swap(float *x, float *y);
9+
int partition(float V[], int low, int high);
10+
void quickSort(float V[], int low, int high);
11+
int bin_pret(float V[], int n, float x);
12+
13+
int main()
14+
{
15+
time_t t1, t2, t3, t4, t5, t6;
16+
int n;
17+
float *A;
18+
19+
printf("Unesite n velicinu polja:\n");
20+
scanf("%d", &n);
21+
22+
A = (float * ) malloc(n * sizeof(float));
23+
24+
gen_arr(A, n, 5, 300);
25+
26+
float trazeni_br = 7;
27+
28+
t1 = clock();
29+
30+
sekv_pret(A, n, trazeni_br);
31+
32+
t2 = clock();
33+
34+
printf("\nVrijeme izmedu sekvecijalnog pr je: %ld ms", (t2 - t1));
35+
36+
37+
t3 = clock();
38+
39+
sort(A, n);
40+
41+
t4 = clock();
42+
43+
printf("\nVrijeme izmedu sortiranja je: %ld ms", (t4 - t3));
44+
45+
t5 = clock();
46+
47+
bin_pret(A, n, trazeni_br);
48+
49+
t6 = clock();
50+
51+
printf("\nVrijeme izmedu binarnog pr je: %ld ms", (t6 - t5));
52+
53+
return 0;
54+
55+
free(A);
56+
}
57+
58+
void gen_arr(float V[], int n, float dg, float gg ) {
59+
srand(time(NULL));
60+
for(int i = 0; i < n; i ++) {
61+
V[i] = dg + ((float) rand() / RAND_MAX) * (gg - dg);
62+
}
63+
}
64+
65+
66+
int sekv_pret( float V[], int n, float x ){
67+
for(int i = 0; i < n; i++){
68+
if(V[i] == x){
69+
return i;
70+
}
71+
}
72+
return -1;
73+
}
74+
75+
void swap(float *a, float *b)
76+
{
77+
float temp = *a;
78+
*a = *b;
79+
*b = temp;
80+
}
81+
82+
83+
int partition(float V[], int low, int high)
84+
{
85+
float pivot = V[high];
86+
int i = low - 1;
87+
for (int j = low; j <= high - 1; j++) {
88+
if (V[j] < pivot) {
89+
i++;
90+
swap(&V[i], &V[j]);
91+
}
92+
}
93+
swap(&V[i+1], &V[high]);
94+
return i+1;
95+
}
96+
97+
98+
void quickSort(float V[], int low, int high)
99+
{
100+
if (low < high) {
101+
int pi = partition(V, low, high);
102+
quickSort(V, low, pi - 1);
103+
quickSort(V, pi + 1, high);
104+
}
105+
}
106+
107+
108+
void sort(float V[], int n)
109+
{
110+
quickSort(V, 0, n-1);
111+
}
112+
113+
114+
int bin_pret(float V[], int n, float x)
115+
{
116+
int left = 0;
117+
int right = n - 1;
118+
while (left <= right) {
119+
int middle = (left + right) / 2;
120+
if (V[middle] == x) {
121+
return middle;
122+
}
123+
else if (V[middle] < x) {
124+
left = middle + 1;
125+
}
126+
else {
127+
right = middle - 1;
128+
}
129+
}
130+
return -1;
131+
}

0 commit comments

Comments
 (0)