步驟 7. 創建函數
最後一步就是創建一個函數來在字符串數組中運行 QuickSort。我們將此函數放到應用程序類 QuickSortApp 之中。
修改源代碼
更改 C# 源文件 (class1.cs),如下面以斜體突出顯示的 代碼所示。其他的差異(如類名)可忽略不計。
// Import namespaces
using System;
using System.Collections;
using System.IO;
// Declare namespace
namespace MsdnAA
{
// Declare application class
class QuickSortApp
{
// Application initialization
static void Main (string[] szArgs)
{
... ... ...
// Pass to QuickSort function
QuickSort (szContents, 0, szContents.Count - 1);
... ... ...
}
// QuickSort implementation
static void QuickSort (ArrayList szArray, int nLower, int nUpper)
{
// Check for non-base case
if (nLower < nUpper)
{
// Split and sort partitions
int nSplit = Partition (szArray, nLower, nUpper);
QuickSort (szArray, nLower, nSplit - 1);
QuickSort (szArray, nSplit + 1, nUpper);
}
}
// QuickSort partition implementation
static int Partition (ArrayList szArray, int nLower, int nUpper)
{
// Pivot with first element
int nLeft = nLower + 1;
string szPivot = (string) szArray[nLower];
int nRight = nUpper;
// Partition array elements
string szSwap;
while (nLeft <= nRight)
{
// Find item out of place
while (nLeft <= nRight)
{
if (((string) szArray[nLeft]).CompareTo (szPivot) > 0)
break;
nLeft = nLeft + 1;
}
while (nLeft <= nRight)
{
if (((string) szArray[nRight]).CompareTo (szPivot) <= 0)
break;
nRight = nRight - 1;
}
// Swap values if necessary
if (nLeft < nRight)
{
szSwap = (string) szArray[nLeft];
szArray[nLeft] = szArray[nRight];
szArray[nRight] = szSwap;
nLeft = nLeft + 1;
nRight = nRight - 1;
}
}
// Move pivot element
szSwap = (string) szArray[nLower];
szArray[nLower] = szArray[nRight];
szArray[nRight] = szSwap;
return nRight;
}
}
}