C#中使用快速排序按檔案建立時間將檔案排序的源碼

來源:互聯網
上載者:User

快速排序類

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.IO;

/// <summary>

/// 快速排序演算法

/// </summary>

public class MyQuickSort

{

public MyQuickSort()

{

//

// TODO: Add constructor logic here

//

}

/// <summary>

/// 快速排序演算法

/// </summary>

/// 快速排序為不穩定排序,時間複雜度O(nlog2n),為同數量級中最快的排序方法

/// <param name="arr">劃分的數組</param>

/// <param name="low">數組低端上標</param>

/// <param name="high">數組高端下標</param>

/// <returns></returns>

static int Partition(FileInfo[] arr, int low, int high)

{

//進行一趟快速排序,返回中心軸記錄位置

// arr[0] = arr[low];

FileInfo pivot = arr[low];//把中心軸置於arr[0]

while (low < high)

{

while (low < high && arr[high].CreationTime <= pivot.CreationTime)

--high;

//將比中心軸記錄小的移到低端

Swap(ref arr[high], ref arr[low]);

while (low < high && arr[low].CreationTime >= pivot.CreationTime)

++low;

Swap(ref arr[high], ref arr[low]);

//將比中心軸記錄大的移到高端

}

arr[low] = pivot; //中心軸移到正確位置

return low; //返回中心軸位置

}

static void Swap(ref FileInfo i, ref FileInfo j)

{

FileInfo t;

t = i;

i = j;

j = t;

}

/// <summary>

/// 快速排序演算法

/// </summary>

/// 快速排序為不穩定排序,時間複雜度O(nlog2n),為同數量級中最快的排序方法

/// <param name="arr">劃分的數組</param>

/// <param name="low">數組低端上標</param>

/// <param name="high">數組高端下標</param>

public static void QuickSort(FileInfo[] arr, int low, int high)

{

if (low <= high - 1)//當 arr[low,high]為空白或只一個記錄無需排序

{

int pivot = Partition(arr, low, high);

QuickSort(arr, low, pivot - 1);

QuickSort(arr, pivot + 1, high);

}

}

}

如使用其它排序演算法請參考: http://www.yaosansi.com/blog/article.asp?id=980

使用方法:

System.IO.DirectoryInfo dir = new DirectoryInfo(currentFolder);

System.IO.FileInfo[] files = dir.GetFiles();

MyQuickSort.QuickSort(files, 0, files.Length - 1);//按時間排序

使用後:

如果files的長度大於0,那麼files[0]為建立時間最新的檔案.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.