Sorting/Searching Flashcards

1
Q

What is Selection sorting?

Time/Space complexity

A

Sort by finding the smallest value and placing it at the first index. Move to the next index and find the next lowest value. Keep iterating until reaching end of the array.
Time Complexity: O(n^2)
Space: O(1)

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

Implement Selection

A
void selectionSort(int[] a) 
	{
		int min = Integer.MAX_VALUE;
		int tmpL = -1;
		for (int i = 0; i < a.length;i++)
		{
			for (int j = i; j < a.length;j++)
			{
				if (min > a[j])
				{
					min = a[j];
					tmpL = j;
				}	
			}
			int tmp = a[i];
			a[tmpL] = tmp;
			a[i] = min;
			min = Integer.MAX_VALUE;
		}
	}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is Insertion sort?

A

Loop for 2 elements in the array. Find the minimum between the two. Increase the searchable array size by 1. Look for the minimum and move it to the first index, shifting other values to the right. Continue until process complete.
Time: O(n^2)
Space: O (1)

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

Implement insertion

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

Merge Sort

A

Merge sort uses divide and conquer to sort an array. It divides an array into two. It recursively divides the subarrays into 2 again and sorts them.
Time(Onlogn)
Space(n)

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

What is Binary Search?

A

Search a sorted array by dividing into 1/2. Compare the middle with the value, if value is greater, perform binary search on right subarray. If lesser, perform Binary search on left subarray.

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

Implement BinarySearch iteratively

A
int bSearchIter(int val, int[] arr)
	{
		int start = 0;
		int end = arr.length-1;
		int mid = (end + start) /2;
		while (start <= end)
		{
			mid = (start +end)/2;
			if (arr[mid] < val)
			{
				start = mid+1;
			}
			else if (arr[mid] > val)
			{
				end = mid-1;
			}
			else
			{
				return mid;
			}
	}
	return -1;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Implement Binary Search Recursively

A
int bSearch(int val, int[] arr, int start, int end) 
	{
		if (start > end ) return -1;
		int mid =(end+start)/2;
		if (arr[mid] == val) return mid;
		else if (arr[mid] < val)
		{
			return bSearch(val,arr, mid+1,end);
		}
		else if (arr[mid] > val)
		{
			return bSearch(val, arr, 0, mid-1);
		}
		return -1;
	}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly