0

Giving an integer array, the ninetieth percentile is the first number that exceeds 90% of the arrays. If you want more specific definition, please look at http://studentnet.cs.manchester.ac.uk/ugt/COMP26120/lab/ex6def.html

I have written a quick select program which works successfully with normal occasions. That is partially sorting which only sorting the side where the 90th percentile contains.

But for the special occasions like if all the integers are same, and there are no 90th percentile, it would still find the 90th number, but not return -1.

Please ensure the program is O(n) after rectified.

If I used a loop in the main function which repeatedly calling quick select function to compare (k-1)th number and kth number, the running time would (n-k)*n=O(n^2) (quick select is in O(n) which i googled) .Is it a easier way to find valid 90th number while selecting?

Here are my codes:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>  
#define N 23

void swap ( int *a, int *b){
    int t;
    t=*a;
    *a=*b;
    *b=t;
}
int partition(int *a, int high){ //high is the last index of this array
    int i,j,pivotValue;
    i = -1;
    j = 0;
    pivotValue = a[high]; 
    for ( j=0; j<high; j++){
        if ( a[j]> pivotValue){
            continue;
        }
        i++;
        swap(&a[i], &a[j]);
    }
    return i+1;
}
int quickSelect(int a[],int n, int k) { //n is the size of the array
    int pivotIndex;
    pivotIndex = partition(a, n-1);
    if ( pivotIndex >= k ){//left.size = pivotIndex
        printf("left\n");

        return quickSelect(a, pivotIndex, k);
    }
    else if ( (pivotIndex+1)==k ){
        printf("pivot\n");
        return a[n-1];
    }
    else{
        printf("right\n");
        return quickSelect(&a[pivotIndex], n-(pivotIndex+1), k-(pivotIndex+1));
    }
}


int main()
{
int a[] = {1612,1894,3018,4212,6046,12894,13379,14408,14615,16394,17982,23004,27588,31393,33195,39526,54326,54566,60000,60000,60000,60000,703908};

    int find,k;

    k = floor(N*0.9)+1;
    printf("k=%d\n",k);

    find = quickSelect(a, N, k);

    printf("the 90th number=%d\n",find);

    return 0;
}
NUO
  • 247
  • 2
  • 3
  • 14
  • QuickSelect is nothing but `partition` of quick sort...and it finds the number in O(kn), where k is `not a small` constant. – vish4071 Dec 11 '15 at 07:50
  • Practically...`k` is never `n` (unless array is sorted and you are not randomizing the pivot, etc.) and is near to `log(n)`. – vish4071 Dec 11 '15 at 08:00

0 Answers0