//快速排序算法C#實現
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace 快速排序算法1
- {
- class Program
- {
- static void Main(string[] args)
- {
- int[] arrays = { 10, 32, 22, 37, 2, 5, 23, 11, 21, 15, 18, 3, 26 };
- Console.WriteLine("進行快速排序前的結果如下:");
- for (int i = 0; i < arrays.Length; i++)
- {
- Console.Write(arrays[i] + " ");
- }
- quickSort(arrays, 0, arrays.Length - 1);
- Console.WriteLine("\n進行快速排序後的結果如下:");
- for (int i = 0; i < arrays.Length; i++)
- {
- Console.Write(arrays[i] + " ");
- }
- Console.ReadKey();
- }
- static void quickSort(int[] arrays, int low, int high)
- {
- // 樞紐元,一般以第一個元素爲基準進行劃分
- int i = low;
- int j = high;
- if (low < high)
- {
- // 從數組兩端交替地向中間掃描
- int key = arrays[low];
- // 進行掃描的指針i,j;i從左邊開始,j從右邊開始
- while (i < j)
- {
- while (i < j && arrays[j] > key)
- {
- j--;
- }// end while
- if (i < j)
- {
- // 比樞紐元素小的移動到左邊
- arrays[i] = arrays[j];
- i++;
- }// end if
- while (i < j && arrays[i] < key)
- {
- i++;
- }// end while
- if (i < j)
- {
- // 比樞紐元素大的移動到右邊
- arrays[j] = arrays[i];
- j--;
- }// end if
- }// end while
- // 樞紐元素移動到正確位置
- arrays[i] = key;
- // 前半個子表遞歸排序
- quickSort(arrays, low, i - 1);
- // 後半個子表遞歸排序
- quickSort(arrays, i + 1, high);
- }// end if
- }
- }
- }