/* Simple arrays for COMP2100
   Richard Walker, 2005
   $Revision: 1.3 $
   $Date: 2005/05/22 07:20:07 $ */

#include <jni.h>
#include <stdlib.h>
#include "IntegerArray.h"

/* Return a pointer to the first element of enough memory to
   store n integers. */
JNIEXPORT jint JNICALL Java_IntegerArray_new_1array(JNIEnv *env,
                                                    jobject obj, jint n){
  return (jint)calloc((int)n, sizeof(int));
}

/* Return the element at index i of the array a. */
JNIEXPORT jint JNICALL Java_IntegerArray_c_1item(JNIEnv *env,
                                                jobject obj, jint a, jint i){
  return (jint)(((int *)a)[i]);
}

/* Insert the value x at index i of array a. */
JNIEXPORT void JNICALL Java_IntegerArray_c_1put(JNIEnv *env,
                                                jobject obj, jint a,
                                                jint x, jint i){
  ((int *)a)[i] = x;
}

/* Exchange the elements at indices i and j of array a. */
JNIEXPORT void JNICALL Java_IntegerArray_c_1swap(JNIEnv *env,
                                                 jobject obj, jint a,
                                                 jint i, jint j){
  int *a_array;
  int tmp;

  a_array = (int *)a;
  tmp = a_array[i];

  a_array[i] = a_array[j];
  a_array[j] = tmp;
}

void c_swap(int a[], int i, int j){
  int tmp = a[i];

  a[i] = a[j];
  a[j] = tmp;
}

void c_sort_descending (int a[], int lo, int hi){
  int pivot;
  int i;
  
  if (lo < hi){
    i = (lo + hi) / 2;
    c_swap(a, lo, i);
    pivot = lo;
    for (i=lo+1; i<=hi; i++){
      if (a[i] > a[lo]){
        pivot++;
        c_swap(a, pivot, i);
      }
    }
    c_swap(a, lo, pivot);
    c_sort_descending(a, lo, pivot - 1);
    c_sort_descending(a, pivot + 1, hi);
  }
}

/* Sort the part of array a from index lo to index hi into
   descending order using the Quicksort algorithm. */
JNIEXPORT void JNICALL Java_IntegerArray_c_1sort_1descending (JNIEnv *env,
                                                              jobject obj,
                                                              jint a, jint lo,
                                                              jint hi){
  c_sort_descending((int *)a, (int)lo, (int)hi);
}

