Advertisement
STANAANDREY

sda p1 pb3

Jan 4th, 2024 (edited)
1,026
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.98 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdbool.h>
  5.  
  6. void swap(void* a, void* b, size_t size) {
  7.     void* tmp = malloc(size);
  8.     if (tmp == NULL) {
  9.         perror("");
  10.         exit(1);
  11.     }
  12.     memcpy(tmp, a, size);
  13.     memcpy(a, b, size);
  14.     memcpy(b, tmp, size);
  15.     free(tmp);
  16. }
  17.  
  18. #define NAME_MAX 35
  19. typedef struct {
  20.     char name[NAME_MAX];
  21.     int salary;
  22.     bool bonus;
  23. } Emp;
  24.  
  25. int moveToBeg(int n, Emp emps[]) {//O(n)
  26.     int le = 0, ri = n - 1;
  27.     while (le < ri) {
  28.         while (emps[le].bonus && le < ri) {
  29.             le++;
  30.         }
  31.         while (!emps[ri].bonus && le < ri) {
  32.             ri--;
  33.         }
  34.         if (le < ri) {
  35.             swap(&emps[le], &emps[ri], sizeof(Emp));
  36.             le++, ri--;
  37.         }
  38.     }
  39.     return le;
  40. }
  41.  
  42. void printEmp(const Emp *const e) {
  43.     printf("{%s %d %d}\n", e->name, e->salary, e->bonus);
  44. }
  45.  
  46. void printEmpArr(int n, const Emp e[]) {
  47.     for (int i = 0; i < n; i++) {
  48.         printEmp(&e[i]);
  49.     }
  50. }
  51.  
  52. void quickSort(Emp emps[], int le, int ri) {
  53.     if (le < ri) {
  54.         int mid = (le + ri) / 2;
  55.         swap(&emps[mid], &emps[le], sizeof(Emp));
  56.         int i = le, j = ri, d = 0;
  57.         while (i < j) {
  58.             if (emps[j].salary > emps[i].salary) {
  59.                 swap(&emps[i], &emps[j], sizeof(Emp));
  60.                 d = 1 - d;
  61.             }
  62.             i += d;
  63.             j -= 1 - d;
  64.         }
  65.         quickSort(emps, le, i - 1);
  66.         quickSort(emps, i + 1, ri);
  67.     }
  68. }
  69.  
  70. int main(void) {
  71.     const int n = 6;
  72.     Emp emps[] = {
  73.         {"john1", 4321, true},
  74.         {"john2", 43, false},
  75.         {"john3", 3, false},
  76.         {"john4", 3222, true},
  77.         {"john5", 213, false},
  78.         {"john6", 333, false},
  79.     };
  80.     //printEmpArr(n, emps);
  81.     int j = moveToBeg(n, emps);
  82.     printEmpArr(n, emps);
  83.     puts("-----------------------");
  84.     printf("%d\n", j);
  85.     quickSort(emps, j, n - 1);
  86.     printEmpArr(n, emps);
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement