Pagini recente » Cod sursa (job #1079819) | Cod sursa (job #1393868) | Cod sursa (job #2637534) | Cod sursa (job #2084005) | Cod sursa (job #1195576)
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void * alocaVector(int numberOfElements) {
void * vector = NULL;
vector = malloc(numberOfElements);
if (vector == NULL) {
fprintf(stderr, "Eroare la alocare");
exit(EXIT_FAILURE);
}
return vector;
}
static int partitioneaza(int *a, int inf, int sup) {
static char init = 0;
int pivot, i, j, aux;
if (init == 0) {
srand((unsigned int) time(NULL));
init = 1;
}
pivot = rand() % (sup - inf);
pivot += inf;
pivot = a[pivot];
i = inf;
j = sup;
while (i <= j) {
while (a[i] < pivot && i < sup)
i++;
while (a[j] > pivot && j > inf)
j--;
if (i <= j) {
aux = a[i];
a[i] = a[j];
a[j] = aux;
i++;
j--;
}
}
return i;
}
void quickSort(int *a, int inf, int sup) {
if (inf < sup) {
int pozitieCorecta;
pozitieCorecta = partitioneaza(a, inf, sup);
if (pozitieCorecta - 1 > inf) {
quickSort(a, inf, pozitieCorecta - 1);
}
if (pozitieCorecta + 1 < sup) {
quickSort(a, pozitieCorecta + 1, sup);
}
}
}
int main() {
freopen("algsort.in", "r", stdin);
freopen("algsort.out", "w", stdout);
int * vector, numarElemente;
int i;
scanf("%d", &numarElemente);
vector = (int *) alocaVector(numarElemente * sizeof(int));
for (i = 0; i < numarElemente; i++) {
scanf("%d", (vector + i));
//vector[i] = numarElemente - i; //(100 * i + i * i - 256 + i * i* i* i - 555)%30;
}
quickSort(vector, 0, numarElemente - 1);
for (i = 0; i < numarElemente; i++) {
printf("%d ", vector[i]);
}
return 0;
}