my code works as far as i can tell.. I was wondering if it can be done in a better way (better time complexity) and what is the time complexity of my code as im not really sure how to caculate it. cant change the current array in the question but if there is a faster way to do it by removal i would also like to know, thanks a lot.
int i = 1, j = 0, count = 1;
int arrNew[SIZE] = { NULL };
arrNew[0] = arr1[0];
while(i<size){
if (arr1[i] == arrNew[j]) { // if the element of arr1 is already added, resets j for next iteration and moves to the next element.
j = 0;
i++;
}
else {
if (j == count - 1) { // checks if we reached the end of arrNew and adds missing element.
arrNew[count] = arr1[i];
j = 0;
count++; // this variable makes sure we check only the assigned elements of arrNew.
i++;
}
else // if j < count -1 we didnt finish checking all of arrNew.
j++;
}
}
jmarches up the original will compare against every already-classified item in the new array. Since they're all unique already, that means sweeps will be 1, 2, 3, 4... (n-2), (n-1) comparisons. That's a worst case O(n^2) result. Fyi, the best-case, is the entire original filled with the same value. That means an immediate jettison after the first compare on each iteration, resulting in only one final value in the array and a O(n) best-case.iorjconditionally, hiding the loop complexity. 2. if permitted, the sanest approach is to do a "sort into new array" (which isO(n log n)), then remove duplicates in a second pass (alternatively, this could be done incrementally using a "partial sort", but this has worse complexity: AFAICTO((n/m)n log(m))if done in chunks of size m), 3. if you want to preserve the original order, you could do approach #2 into a temporary buffer, then allocate a bitset and do another pass over the input, doing a binary search and marking it.