简体   繁体   中英

how can I remove a duplicates from sorted array?

what I'm supposed to do is to sort a list of prices and choose one of the values as ordered but there are duplicated prices in the array how can I remove them?

I have like 9 arrays and I need to sort them and print out the value of the order (lowest price, second lowest price, etc..) sorry for not clearing that out.

int lowestPrice(int array[], int size, int order){

int tempArray[size];
    
    for (size_t i = 0; i < size; i++)
        tempArray[i] = array[i];

    for (size_t i = 0; i < size; i++)
        for (size_t j = i; j < size; j++)
            if (tempArray[j] < tempArray[i]) {
                int tmp = tempArray[i];
                tempArray[i] = tempArray[j];
                tempArray[j] = tmp;
            }
    int j = 0;
    for (size_t i = 0; i < size -1; i++){
        if(tempArray[i] != tempArray[i+1])
        {
            tempArray[j] = tempArray[i];
            j++;
        } tempArray[j] = tempArray[i-1];
    }

    return tempArray[order];    
}

You should replace your last "for" with:

int j = 0;
for (size_t i = 1; i < size ; i++){
    if(tempArray[i] != tempArray[i-1])
    {
        tempArray[j] = tempArray[i];
        j++;
    }
}

What you want to do is to keep the first one of each number, so if the current one is equal to the last one, it will ignore it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM