Wednesday, July 26, 2017

partition

void swap(int a[], int i, int j) //swaps values using their indices
{
  int x = a[i];
  a[i] = a[j];
  a[j] = x;
}

int partition(int list[], int len)
{
  int pivot = list[0];
  int pi = 0; //pivot starting index
  int i = 0; int j = len-1;
  while(i!=j){
    if(pi == i){
      if(list[j] < pivot){
        swap(list,i,j);
        pi = j;
        i++;
      } else { //when the j->val is greater than pivot
        j--;
      }
    }else{//when the pivot index is at the j value instead
      if(list[i] > pivot){
        swap(list, i, j);
        pi = i;
        j--;
      } else {
        i++;
      }
    }
  }
  return pi;
}

int main ()
{
    int arr[8] = {6,1,7,5,8,9,3,2};
    int len = 8;
    int first = arr[0];
    int count = 0;
    partition(arr, len);

    for(int i=0; i<len; i++){
        printf("%d", arr[i]);
    }
    return 0;
}

No comments:

Post a Comment