當我嘗試執行以下代碼時,會導致分段錯誤。使用在線 GDB 程式在第一次呼叫磁區函式后停止作業。partition()該程式從不進行遞回,并在呼叫后立即停止作業。
#include <stdio.h>
int partition(int arr[], int len)
{
int pivot = len / 2;
int left = 0;
int right = len - 1;
int temp;
while (right != 0 || left !=0)
{
if (right != pivot)
{
if (arr[right] < arr[pivot])
{
temp = arr[right];
arr[right] = arr[pivot];
arr[pivot] = temp;
pivot = right;
}
else right--;
}
else
{
if (arr[left] > arr[pivot])
{
temp = arr[left];
arr[left] = arr[pivot];
arr[pivot] = temp;
pivot = left;
}
else left ;
}
}
return pivot;
}
void quicksort(int arr[], int len)
{
if (len > 1)
{
int pivot = partition(arr, len);
quicksort(arr, pivot);
quicksort(arr pivot 1, len-pivot-1);
}
}
int main()
{
int arr[] = {1,6,3,2,9,5,4,7,8};
quicksort(arr, 9);
for (int i =0; i< 9; i )
{
printf("%d ", arr[i]);
}
return 0;
}
出于某種原因,當呼叫磁區函式時,變數 pivot、left、right 都被初始化為垃圾值。
請幫忙。
uj5u.com熱心網友回復:
您的主要while條件(right != 0 || left !=0)有缺陷。所需要的只是一個下限碰撞通道else left ',并且該條件將是永久的,最終導致段突破。
相反,您希望左右折疊,直到它們達到共同點為止。前任:while (right > left)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/468813.html
上一篇:無法確定并列印從int到float隱式轉換的截斷錯誤
下一篇:在C中使用AVX實作矩陣運算
