Select the appropriate code that performs gnome sort.

Trần Vũ

New member
Select the appropriate code that performs gnome sort.
A.
Code:
while (index > n) 
{ 
        if (index == 0) 
            index++; 
        if (arr[index] <= arr[index - 1]) 
            index++; 
        else 
        { 
            swap(arr[index], arr[index - 1]); 
            index--; 
        } 
}
B.
Code:
while (index < n) 
{ 
        if (index == 0) 
            index++; 
        if (arr[index] <= arr[index - 1]) 
            index++; 
        else 
        { 
            swap(arr[index], arr[index - 1]); 
            index--; 
        } 
}
C.
Code:
while (index < n) 
{ 
        if (index == 0) 
            index++; 
        if (arr[index] >= arr[index - 1]) 
            index++; 
        else 
        { 
            swap(arr[index], arr[index - 1]); 
            index--; 
        } 
}
D.
Code:
while (index < n) 
{ 
        if (index == 0) 
            Index--; 
        if (arr[index] >= arr[index - 1]) 
            index++; 
        else 
        { 
            swap(arr[index], arr[index - 1]); 
            Index++; 
        } 
}
 
Answer: c
Explanation: The first if statement increments the value of index if found to be 0 so that comparison can take place for this element. Second if statement checks whether the adjacent pair of elements are in order or not. If found out of order they are swapped under the else statement and index is decremented.
 

Tìm kiếm

Back
Top