首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Visual C# .NET 入門指南(六)

     編輯:關於C語言

步驟 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;
        }
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved