Choose the correct function for recursive insertion sort?

Choose the correct function for recursive insertion sort?
A.
Code:
void RecInsertionSort(int arr[], int n) 
{ 
	if (n <= 1) 
		return; 
	RecInsertionSort( arr, n-1 ); 	
	int key = arr[n-1]; 
	int j = n-2; 	
	while (j >= 0 && arr[j] > key) 
	{ 
		arr[j+1] = arr[j]; 
		j--; 
	} 
	arr[j+1] = key; 
}
B.
Code:
void RecInsertionSort(int arr[], int n) 
{ 
	if (n < 1) 
		return; 
	RecInsertionSort( arr, n-1 ); 
	int key = arr[n-1]; 
	int j = n-2; 
	while (j >= 0 || arr[j] > key) 
	{ 
		arr[j+1] = arr[j]; 
		j--; 
	} 
	arr[j] = key; 
}
C.
Code:
void RecInsertionSort(int arr[], int n) 
{ 
	if (n <1) 
		return; 
	RecInsertionSort( arr, n-1 ); 
	int key = arr[n-1]; 
	int j = n-2; 
	while (j >= 0 && arr[j] > key) 
	{ 
		arr[j+1] = arr[j]; 
		j--; 
	} 
	arr[j] = key; 
}
D.
Code:
void RecInsertionSort(int arr[], int n) 
{ 
	if (n <= 1) 
		return; 
	RecInsertionSort( arr, n-1 ); 
	int key = arr[n-1]; 
	int j = n-1; 
	while (j >= 0 || arr[j] > key) 
	{ 
		arr[j+1] = arr[j]; 
		j--; 
	} 
	arr[j+1] = key; 
}
 
Answer: a
Explanation: The base case of recursive bubble sort should be when n equal or less than 1 then return. Also we need to insert the element being chosen as key at its correct position in the sorted array to its left. All this needs to be done in a recursive code.
 

Tìm kiếm

Back
Top