温馨提示×

c#快速排序的递归与非递归形式

c#
小樊
100
2024-06-25 23:41:54
栏目: 编程语言

递归形式的C#快速排序算法:

using System; class QuickSort { public static void Sort(int[] arr, int low, int high) { if (low < high) { int pivot = Partition(arr, low, high); Sort(arr, low, pivot - 1); Sort(arr, pivot + 1, high); } } public static int Partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j < high; j++) { if (arr[j] < pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp1 = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp1; return i + 1; } public static void PrintArray(int[] arr) { foreach (int num in arr) { Console.Write(num + " "); } Console.WriteLine(); } public static void Main() { int[] arr = { 12, 11, 13, 5, 6, 7 }; int n = arr.Length; Console.WriteLine("Original array:"); PrintArray(arr); Sort(arr, 0, n - 1); Console.WriteLine("Sorted array:"); PrintArray(arr); } } 

非递归形式的C#快速排序算法:

using System; using System.Collections.Generic; class QuickSort { public static void Sort(int[] arr, int low, int high) { Stack<int> stack = new Stack<int>(); stack.Push(low); stack.Push(high); while (stack.Count > 0) { high = stack.Pop(); low = stack.Pop(); int pivot = Partition(arr, low, high); if (pivot - 1 > low) { stack.Push(low); stack.Push(pivot - 1); } if (pivot + 1 < high) { stack.Push(pivot + 1); stack.Push(high); } } } public static int Partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j < high; j++) { if (arr[j] < pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp1 = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp1; return i + 1; } public static void PrintArray(int[] arr) { foreach (int num in arr) { Console.Write(num + " "); } Console.WriteLine(); } public static void Main() { int[] arr = { 12, 11, 13, 5, 6, 7 }; int n = arr.Length; Console.WriteLine("Original array:"); PrintArray(arr); Sort(arr, 0, n - 1); Console.WriteLine("Sorted array:"); PrintArray(arr); } } 

0