Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<time.h>
- #include<math.h>
- void swap(float *p1, float *p2){
- float temp;
- temp = *p1;
- *p1 = *p2;
- *p2 = temp;
- }
- void gen_arr(float *p, int n, float dg, float gg){
- int i;
- for (i = 0; i < n; i++){
- p[i] = dg + (float)rand() / RAND_MAX*(gg - dg);
- }
- }
- int sekv_pret(float *p, int n, float x){
- int i,a=-1;
- for (i = 0; i < n; i++){
- if (p[i] == x){
- a = i;
- break;
- }
- }
- return a;
- }
- void sort(float p[], int low,int high){
- int s = p[(low + high) / 2];
- int i = low, j = high;
- while (i <= j) {
- while (p[i] < s) {
- i++;
- }
- while (p[j] > s)
- {
- j--;
- }
- if (i <= j) {
- swap(&p[i], &p[j]);
- i++;
- j--;
- }
- }
- }
- int bin_pret(float p[], int n, float x){
- int dg=0, gg=n-1,s,a=-1;
- while (dg <= gg){
- s = (dg + gg) / 2;
- if (x == p[s]){
- printf("Broj je pronađen na %d. mjestu.", s);
- a = s;
- break;
- }
- else if (x > p[s]){
- dg = s + 1;
- }
- else if (x < p[s]) {
- gg = s - 1;
- }
- }
- return a;
- }
- int main(){
- int n,x;
- float *p,dg,gg;
- time_t t1, t2;
- srand(time(NULL));
- printf("\nUnesite velicinu polja:");
- scanf("%d", &n);
- p = (float*)malloc(n*sizeof(float));
- printf("\nUnesite donju i gornju granicu polja:");
- scanf("%f%f", &dg, &gg);
- gen_arr(p, n, dg, gg);
- printf("\nUnesite x:");
- scanf("%d", &x);
- t1 = clock();
- int sp = sekv_pret(p, n, x);
- t2 = clock();
- if (sp == -1)
- printf("\nBroj se ne nalazi u polju.");
- else printf("\nBroj se nalazi na %d mjestu.", sp + 1);
- printf("\nVrijeme trajanja sekvencijalnog pretrazivanja je:%d ms\n", t2 - t1);
- t1 = clock();
- sort(p, 0,n-1);
- t2 = clock();
- printf("\nVrijeme trajanja sortiranja je:%d ms\n", t2 - t1);
- t1 = clock();
- int bp = bin_pret(p, n, x);
- t2 = clock();
- if (bp == -1)
- printf("\nBroj se ne nalazi u polju.");
- else printf("\nBroj se nalazi na %d mjestu.", sp + 1);
- printf("\nVrijeme trajanja brinarnog pretrazivanja je:%d ms", t2 - t1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement