我寫了我在c#中的快速排序算法,但它有一個問題,當我編譯它,它不工作在一些條件,例如,當我輸入數字12,32,11在textbox6排序,它給出了範圍的錯誤,當我去跟蹤它,調試器顯示,NUM []把NUMS [0] = 12,NUMS [1] = 11,NUMS [2] = 1在C#中使用QuickSort算法的問題#
編輯: 我改變while條件,它知道犯規給超出範圍的錯誤,但是當輸入爲12,32,11輸出11,12,1
private void button5_Click(object sender, EventArgs e)
{
string[] x = textBox6.Text.Split(',');
int[] nums = new int[x.Length];
for (int counter = 0; counter < x.Length; counter++)
{
nums[counter] = Convert.ToInt32(x[counter]);
}
int i = 0;
int j = nums.Length;
int pivot = nums[0];
do
{
do
{
i++;
}
while ((i < nums.Length) && (nums[i] < pivot));
do
{
j--;
}
while (nums[j]>pivot);
if (i < j)
{
int temp = i;
nums[i] = nums[j];
nums[j] = temp;
}
}while(i<j);
int temp1 = nums[0];
nums[0] = nums[j];
nums[j] = temp1;
int pivotpoint = j;
string QuickSort = "";
foreach (var n in nums)
QuickSort += n.ToString() + ",";
textBox5.Text = QuickSort;
}
也許你應該張貼的完整代碼...無論如何,在一個按鈕的事件處理程序似乎並不像實現快速排序一個非常好的主意...... – 2010-12-19 11:22:13
1)你沒有發佈完整的循環。 2)我看不到遞歸。那麼這應該如何快速排序呢? – CodesInChaos 2010-12-19 11:27:39
我編輯了我的問題並粘貼完整的代碼 – Arash 2010-12-19 11:31:02