#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int hoare(int* arr, int i, int j, int idx) {
  printf("I: %d, J: %d, IDX: %d\n", i, j, idx);
  if (idx < i) {
    return 0xdeadbeef;
  }

  if (idx > j) {
    return 0xdeadbeef;
  }

  int v;
  int x1,x2;
  int t;
  while (i < j - 1) {
    v = arr[(i + j) / 2];
    printf("Round: (%d,%d) - v: %d\n", i, j, v);
    // sorting on three partitions

    x1 = i;
    x2 = j;

    while (x1 < x2) {

      while (x1 < x2 && arr[x1] <= v) { 
        printf("x1: %d, arr[x1]: %d\n", x1, arr[x1]);
        x1++;
      }

      while (x1 < x2 && arr[x2] >  v) { 
        printf("x2: %d, arr[x2]: %d\n", x2, arr[x2]);
        x2--;
      }

      printf("X1 %d to swap %d\n", x1, arr[x1]);
      printf("X2 %d to swap %d\n", x2, arr[x2]);

      // if x1 == x2, the change makes no difference

      t = arr[x1];
      arr[x1] = arr[x2];
      arr[x2] = t;

    }

    if (arr[x1] > v) x1--; // we could cross == element by

    x2 = x1;
    x1 = i;

    while (x1 < x2) {

      while (x1 < x2 && arr[x1] < v) { 
        printf("x1: %d, arr[x1]: %d\n", x1, arr[x1]);
        x1++;
      }

      while (x1 < x2 && arr[x2] == v) { 
        printf("x2: %d, arr[x2]: %d\n", x2, arr[x2]);
        x2--;
      }

      printf("X1 %d to swap %d\n", x1, arr[x1]);
      printf("X2 %d to swap %d\n", x2, arr[x2]);

      // if x1 == x2, the change makes no difference

      t = arr[x1];
      arr[x1] = arr[x2];
      arr[x2] = t;

    }

    if (x1 > idx) {
      printf("Changing j %d to %d\n", j, x1);
      j = x1;
    } else {
      // x1 <= idx
      printf("Changing i %d to %d\n", i, x1);
      i = x1;
    }
  }

  // we should have i == j == idx
  printf("i: %d, j: %d, idx: %d, v: %d\n", i, j, idx, arr[idx]);
  return arr[idx]; // in order to make it work, we need to make sure that in this place is fully sorted, one way is to split into three pieces
}

/**
 * n: 4
 * 4
 * 3
 * 2
 * 1
 * idx: 4, 3, 2, 1 all work
 */

int main() {

  int n;
  printf("Provide n: ");
  scanf("%d", &n);

  int numbers[n];

  for (int i = 0; i < n; i++) {
    scanf("%d", &numbers[i]);
  }

  int idx;
  printf("Idx: ");
  scanf("%d", &idx);

  int res = hoare(numbers, 0, n-1, idx);
  printf("Res: %x\n", res);
  return 0;
}
