#include <stdio.h> #include <stdlib.h> int quickselect( int *A, int k, int n); i
ID: 3585128 • Letter: #
Question
#include <stdio.h>
#include <stdlib.h>
int quickselect( int *A, int k, int n);
int main(void)
{
long i;
int *space; int tmp;
space = (int *) malloc( 1000000*sizeof(int));
for( i=0; i< 500000; i++ )
{ *(space + i) = ((139*i)%500000);
*(space + i + 500000) = 1000000 + ((141*i)%500000);
}
if( (tmp = quickselect( space, 500001, 1000000)) != 1000000 )
{ printf(" Failed test 1. Returned %d instead of 1000000 ", tmp);
fflush(stdout); exit(-1);
}
else printf("passed test1 ");
for( i=0; i< 500000; i++ )
{ *(space + i) = ((139*i)%500000);
*(space + i + 500000) = 1000000 + ((141*i)%500000);
}
if( (tmp = quickselect( space, 1, 1000000)) != 0 )
{ printf(" Failed test 2. Returned %d instead of 0 ", tmp);
fflush(stdout); exit(-1);
}
else printf("passed test2 ");
for( i=0; i< 500000; i++ )
{ *(space + i) = ((139*i)%500000);
*(space + i + 500000) = 1000000 + ((141*i)%500000);
}
if( (tmp = quickselect( space, 124, 1000000)) != 123 )
{ printf(" Failed test 3. Returned %d instead of 123 ", tmp);
fflush(stdout); exit(-1);
}
else printf("passed test3 ");
printf("Quickselect successful ");
exit(0);
}
Explanation / Answer
Here is the quickSelect code for you:
int quick(int array[],int low,int high)
{
int pivot,rb;
pivot = low;
rb = high;
while(low <=high)
{
while(array[pivot] >= array[low] && low <=rb)
{ low++; }
while(array[pivot] < array[high])
{ high--; }
if(pivot != high)
{
array[pivot] = array[pivot] + array[high];
array[high ] = array[pivot] - array[high];
array[pivot] = array[pivot] - array[high];
}
}
return high;
}
int quicksort(int array[],int k, int low,int high)
{
int pivot;
if(low <= high)
{
pivot = quick(array,low,high);
if(pivot == k)
return array[pivot];
else if(pivot > k)
return quicksort(array,k,low,pivot-1);
else
return quicksort(array,k,pivot+1,high);
}
}
int quickselect(int *A, int k, int n)
{
return quicksort(A, k, 0, n-1);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.