Algorithms Flashcards
space complexity for the sorting algorithms
IDK
for(int i =0 ; I < n; I++)
for(j =0 ; j < I ; j++)
how man times does the second loop perform?
what is the complexity of these two?
- n * (n - 1) / 2
- O(n**2)
if you have a difficult loops to analyze, what should you do?
you should trace the variables (I,j)..
what is the complexity time for
for( I = 0 ; I < n, I++)
O(n)
what is the complexity time for
for( I = 0 ; I < n, I= I+2)
n/2 = O(N)
what is the complexity time for
for( I = 0 ; I < n, I–)
o(n)
what is the complexity time for
for( I = 0 ; I < n, I= I*2)
O(logn)
how we determined what sorting algorithm to use?
- Time Complexity
- Space Complexity
- Internal Sort or External Sort:
Internal: load the data into memory
External Sort: data on disk - Recursive or Non recursive
explain Selection sort shortly
select the minimum and and move it to the sorted part at the beginning.
what is the psudu code for selection sort
for I in range(n -1):
iMin = I
for j in range(I+1, n):
if A[j] < A[iMin]:
iMin=j
temp = A[I]
A[I] = A[iMin]
A[iMin] = temp
com = O(N**2)
can you explain Bubble Sort shortly?
we move the large elements to the right by swapping the left element (large) with right element(small).
what is the pseudo code for Bubble sort?
how can you improve the regular Bubble sort?
for k in range(1, n - 1):
for I in range (0, n -k -1): # -k because the right elements are sorted.
If A[I] > A[I + 1]:
swap(A[I], A[I+1])
Com = O(N**2)
we can improve it by adding flag on the big loop, when we have swap we change it to true, and before we finish the big loop, we check if it’s false. so we can return