快速排序

    技术2026-04-12  5

    class Program { public class Tree { public int data;//数据 public Tree left;//左子树 public Tree right;//右子树 public static void Insert(Tree tree, int num) { if (tree.data <= num) { if (tree.right != null) { Insert(tree.right, num); } else { Tree right = new Tree { data = num }; tree.right = right; } } else { if (tree.left != null) { Insert(tree.left, num); } else { Tree left = new Tree { data = num }; tree.left = left; } } } //树的遍历 public static void Travel(Tree tree) { if (tree.left != null) Travel(tree.left); Console.Write(tree.data + " "); if (tree.right != null) Travel(tree.right); } } public static Tree tree; public static void sort(int[] a) { tree = new Tree { data = a[0] }; for (int i = 1; i < a.Length; i++) { Tree.Insert(tree, a[i]); } } static void Main(string[] args) { //string str= Console.ReadLine(); //string[] array = str.Split(','); //List<int> intArray = new List<int>(); //foreach (string i in array) //{ // intArray.Add(Convert.ToInt32(i)); //} int[] a = { 3, 5, 3, 6, 4, 7, 5, 7, 4, 1, 15, 8, 10, 9 }; Console.WriteLine("原始数据"); foreach (var item in a) { Console.Write(item + " "); } Console.WriteLine(); Console.WriteLine("排序后数据"); sort(a); Tree.Travel(tree); Console.ReadLine(); } private static int DivisionLeft(List<int> list,int left,int right) { while (left<right) { int num = list[left];//中轴 if(num>list[left+1]){ list[left] = list[left + 1]; list[left + 1] = num; left++; } else { int temp = list[left+1]; list[left+1] = list[right]; list[right] = temp; right--; } } return left; } //获取按枢轴值左右分流后枢轴的位置 private static int Division(List<int> list, int left, int right) { while (left < right) { int num = list[left]; //将首元素作为枢轴 if (num > list[left + 1]) { list[left] = list[left + 1]; list[left + 1] = num; left++; } else { int temp = list[right]; list[right] = list[left + 1]; list[left + 1] = temp; right--; } Console.WriteLine(string.Join(",", list)); } Console.WriteLine("--------------\n"); return left; //指向的此时枢轴的位置 } }

     

    Processed: 0.013, SQL: 9