2017-04-07 131 views
0

我正在嘗試快速排序。但是,我有一些問題,下面快速排序迭代

for (int current = 0; current <= high - 1; current++) 

環部當我初始化「當前」聲明爲0,則顯示在屏幕上什麼當我運行它。然後,我嘗試用提供的實現中的'低'參數來替換它,並且它運行得當。

我想問的是,爲什麼它不起作用,當我初始化循環語句與0,這是分配給'低'參數相同的值?我試圖用0初始化新變量並將該變量用於循環,但它給出了相同的結果,例如當我直接將循環語句賦值爲0.感謝您的答案。

這裏的代碼:

int partition(int arr[], int low, int high) 
{ 
    int pivot = arr[high]; 
    int index = (low - 1); 
    for (int current = low; current <= high - 1; current++) 
    { 
     if (arr[current] <= pivot) 
     { 
      index++; 
      swap(arr[index], arr[current]); 
     } 
    } 
    swap(arr[index+1], arr[high]); 
    return (index + 1); 
} 

void quicksort(int arr[], int low, int high) 
{ 
    if (low < high) 
    { 
     int pi = partition(arr, low, high); 
     quicksort(arr, low, pi - 1); 
     quicksort(arr, pi + 1, high); 
    } 
} 


int main() 
{ 
    int arr[] = { 3, 4, 2, 5, 1 }; 
    int n = sizeof(arr)/sizeof(arr[0]); 
    quicksort(arr, 0, n-1); 
    for (int i = 0; i < n; i++) 
    { 
     cout << arr[i] << " "; 
    } 
} 

The result when i set the 'current' value with 0

+0

遞歸調用使用相同的陣列,而應該只對自己的一部分工作。當你從0開始電流時,你違反了這部分遞歸調用的「協議」 –

回答

1

low是僅在第一次調用partition 0;在其他調用中需要不同的值。請注意,當quicksort自稱第二次時,low將被分配到pi + 1

打印出來在partition開始觀察這對一些已知不太大陣 - 這應該是一般良好的教育運動。我的意思是使partition第一行:

cout << "low = " << low << "\n";