A array a is given with n elements, and we need to swap the elements d number of times. The below code works fine for smaller n and d values, but when the n and d values are in the order of 10^5. The time consumed is huge. How do I optimize the code?
for(int i=0;i<d;i++){
int j=0;
while((j<n-1)){
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
j++;
}
}
And could you recommend good sources to learn about time complexity and code optimization?
dtimes. Removing the outer loop would make itdtimes faster.Listinstead ofArray. with list you can remove object on one position, and add it on other