Choose the correct function for binary insertion sort?

Thanh Hoan

New member
Choose the correct function for binary insertion sort?
A.
Code:
void BinaryinsertionSort(int a[], int n) 
{ 
    int key; 
    for (int i = 1; i <=n-1; ++i) 
    { 
        int j = i - 1; 
        key = a[i]; 
       //function binarySearch() returns the index
        int index = binarySearch(a, key, 0, j);  
       //where the key should be inserted        
        while (j >= index) 
        { 
            a[j+1] = a[j]; 
            j--; 
        } 
        a[j+1] = key; 
    } 
}
B.
Code:
void BinaryinsertionSort(int a[], int n) 
{ 
    int key; 
    for (int i = 1; i < =n-1; ++i) 
    { 
        int j = i - 1; 
        key = a[i]; 
        //function binarySearch() returns the index
        int index = binarySearch(a, key, j,0);  
        //where the key should be inserted
        while (j >= index) 
        { 
            a[j+1] = a[j]; 
            J++; 
        } 
        a[j+1] = key; 
    } 
}
C.
Code:
void BinaryinsertionSort(int a[], int n) 
{ 
    int key;   
    for (int i = 1; i <=n-1; ++i) 
    { 
        int j = i - 1; 
        key = a[i]; 
        //function binarySearch() returns the index
        int index = binarySearch(a, key, 0, j);  
        //where the key should be inserted        
        while (j <= index) 
        { 
            a[j+1] = a[j]; 
            j--; 
        } 
        a[j+1] = key; 
    } 
}
D.
Code:
void BinaryinsertionSort(int a[], int n) 
{ 
    int key; 
    for (int i = 1; i <=n-1; ++i) 
    { 
        int j = i - 1; 
        key = a[i]; 
        //function binarySearch() returns the index
        int index = binarySearch(a, key, 0, j); 
        //where the key should be inserted        
        while (j <= index) 
        { 
            a[j+1] = a[j]; 
            J++; 
        } 
        a[j+1] = key; 
    } 
}
[/i][/i][/i][/i]
 
Answer: a
Explanation: The code of binary insertion sort is same as the standard insertion sort except that we are finding the index where the key has to be inserted by using binary search. This reduces the number of comparisons.
 

Tìm kiếm

Back
Top