Sorting Flashcards

1
Q

Bubble Sort

A

In bubble sort, in every iteration the next greater element bubbles up to its correct position.

So we need to iterate as follows:

for i from 0 to n-1:
for j from 0 to n-i-1:
if arr[j] > arr[j+1]: swap

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Insertion Sort

A
for (int i = 1; i < n; i++){
    int key = arr[i];
    int j =i;
    while(j > 0 &amp;&amp; arr[j-1] > key){
        arr[j] = arr[j-1];
        j--;
    }
    arr[j] = key; 
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Count Inversions in a Sorted Array

A

In a sorted array, 2 elements form an inversion if a[i] > a[j] and i < j.

def merge_modified(a,n,l,r):
    count = 0
    if l>=r: return count
    count += merge_modified(a,n,l,mid)
    count += merge_modified(a,n,mid+1,r)
    count += merge(a,n,l,mid,r)

At any step in merge(), if a[i] is greater than a[j], then there are (mid – i) inversions.

i=l
j = mid+1
while i<= mid and j <= r:
        if a[i] > a[j]:
            count += mid-i+1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Count Possible Triangles in Unsorted Array

A

Method 1: Sort the array. Take i =0, j= i+1 and find greatest k such that a[k] < a[i] + a[j}. Then we know no of triangles form by i, j as 2 sides are k-j-1.
Then increment j by 1 and now use previous value of k

Method 2: Sort the array. Take i=n-1, l=0, r= i-1 and while l

How well did you know this?
1
Not at all
2
3
4
5
Perfectly