Quicksort and file rearrange
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
|
||||
enum PivotStrategy { RIGHTMOST = 0, MIDDLE = 1, RANDOM = 2 };
|
||||
|
||||
void swap(int *a, int *b) {
|
||||
int temp = *a;
|
||||
*a = *b;
|
||||
*b = temp;
|
||||
}
|
||||
|
||||
int partition(int A[], int left, int right, int pivot_strategy, int length) {
|
||||
int pivot_index;
|
||||
if (pivot_strategy == RIGHTMOST) {
|
||||
pivot_index = right;
|
||||
} else if (pivot_strategy == MIDDLE) {
|
||||
pivot_index = (left + right) / 2;
|
||||
} else if (pivot_strategy == RANDOM) {
|
||||
pivot_index = (rand() % (length + 1));
|
||||
}
|
||||
|
||||
int pivot = A[pivot_index];
|
||||
swap(&A[pivot_index], &A[right]);
|
||||
int i = left - 1;
|
||||
|
||||
for (int j = left; j < right; j++) {
|
||||
if (A[j] <= pivot) {
|
||||
i++;
|
||||
swap(&A[i], &A[j]);
|
||||
}
|
||||
}
|
||||
swap(&A[i + 1], &A[right]);
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
void quicksort(int A[], int p, int r, int pivot_strategy, int length) {
|
||||
if (p < r) {
|
||||
int q = partition(A, p, r, pivot_strategy, length);
|
||||
quicksort(A, p, q - 1, pivot_strategy, length);
|
||||
quicksort(A, q + 1, r, pivot_strategy, length);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int size, pivot_strategy;
|
||||
|
||||
if (scanf("%d", &size) != 1) {
|
||||
fprintf(stderr, "Error reading size\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (scanf("%d", &pivot_strategy) != 1) {
|
||||
fprintf(stderr, "Error reading pivot strategy\n");
|
||||
return 1;
|
||||
}
|
||||
// Init the random number generator when needed
|
||||
if (pivot_strategy == RANDOM) {
|
||||
srand(size);
|
||||
}
|
||||
|
||||
int *array = malloc(sizeof(int) * size);
|
||||
if (array == NULL) {
|
||||
fprintf(stderr, "Memory allocation failed\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (scanf("%d", &array[i]) != 1) {
|
||||
fprintf(stderr, "Error reading array element\n");
|
||||
free(array);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
quicksort(array, 0, size - 1, pivot_strategy, size);
|
||||
|
||||
free(array);
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user