Cod sursa(job #3241535)

Utilizator vralexRadu Vasilescu vralex Data 31 august 2024 12:06:19
Problema Sortare prin comparare Scor 40
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <stdio.h>
#include <stdlib.h>
// #include <time.h>

void swap(int *x, int *y) {
  int aux = *x;
  *x = *y;
  *y = aux;
}

int partition(int *nums, int numsSize, int pivotIndex) {
  int *current, *end = nums;
  swap(&nums[pivotIndex], &nums[numsSize - 1]);
  for (current = nums; current < nums + (numsSize - 1); current++) {
    if (*current < nums[numsSize - 1]) {
      swap(current, end);
      end++;
    }
  }
  swap(end, &nums[numsSize - 1]);
  return end - nums;
}

// Here, numsSize is the size = number of elements of the nums array.
void quicksort(int *nums, int numsSize) {
  if (numsSize <= 1) return;
  // int pivotIndex = rand() % numsSize;
  // int pivot = nums[pivotIndex];
  int pos = partition(nums, numsSize, numsSize - 1);
  // Recursive calls on smaller arrays.
  quicksort(nums, pos);
  // pos+1, ... numsSize-1 (numsSize-1-pos)
  quicksort(nums + pos + 1, numsSize - 1 - pos);
}

int main() {
  int *v, n, i;
  FILE *fp_in, *fp_out;
  fp_in = fopen("algsort.in", "r");
  fp_out = fopen("algsort.out", "w");
  // srand(time(NULL));
  fscanf(fp_in, "%d\n", &n);
  v = (int *)malloc(n * sizeof(int));
  for (i = 0; i < n; i++) fscanf(fp_in, "%d ", &v[i]);
  quicksort(v, n);
  for (i = 0; i < n; i++) fprintf(fp_out, "%d ", v[i]);
  fclose(fp_in);
  fclose(fp_out);
  return 0;
}