Vissza

Labor 14

F
üggvények, mint paraméterek
  1. Egy adott tömb elemeit rendezzük növekvő sorrendbe, Bubblesort algoritmussal; a rendezési függvény tetszőleges típusú tömb rendezésére alkalmas. ( Forráskód )
  2. Egy adott tömb elemeit rendezzük növekvő sorrendbe, Insert-sort és Minimum_Select-sort algoritmussal. A rendezési függvények tetszőleges típusú tömb rendezésére legyenek alkalmasak.

Fel 1.
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>

typedef void* TYPE;

void MySort(TYPE a, unsigned int n, unsigned int size,int(*)(const void *, const void *) );
int comp(const void *a1, const void *a2);

int main(){
    double v[] = { 11.45, -10.3, 11, 2, -9.34, 12, -4, -3.25, 20.30, 10.25};
    unsigned int n,i;
    n= sizeof(v)/sizeof(double);
    MySort(v, n, sizeof(double), comp);
    for (i=0; i<n; i++)
        printf("%7.2lf",v[i]);
    printf("\n");
    return 0;
}

void MySort(TYPE a, unsigned int n, unsigned int size, int(*cp)(const void *a1, const void *a2))
{
    unsigned int i,j;
    TYPE temp,t1,t2;
    temp = malloc(size);
    t1 = malloc(size);
    t2 = malloc(size);
    t1 = a;
    for(i=0; i<n-1; i++)
    {
        t2 = (char*)t1 + size; //a kovetkezo memoriacim elerese
        for(j=i+1; j<n; j++)
        {
            if( cp(t1, t2)<0 )
            {
                memcpy(temp, t1, size);
                memcpy(t1, t2, size);
                memcpy(t2, temp, size);
            }
            t2 = (char*)t2 + size;
        }
        t1 = (char*)t1 + size;
    }
}
Vissza