class ElementsInS ...{ staticvoid Main(string[] args) ...{ Console.WriteLine("请输入数组S中的元素,以","分开");//输入数组S string s =Console.ReadLine(); //生成数组S string[] a = s.Split(','); List<int> ls =new List<int>() ; foreach(string t in a) ...{ int i; if(int.TryParse(t,out i)) ls.Add(i); } Console.WriteLine("请输入数字S:"); int x =int.Parse(Console.ReadLine()); //输入和x int[] aa =newint[ls.Count]; //从List copy数组s ls.CopyTo(aa,0); myQuickSort(aa, 0, ls.Count-1); //先对其进行快速排序时间复杂度为O(nlgn) //以下循环一遍寻找两个元素 int f =0; int l = aa.Length-1; while(f<l) ...{ if(aa[f]+aa[l] == x) ...{ Console.WriteLine("已经找到S的俩元素:"+ aa[f].ToString() +"和"+ aa[l].ToString()); break; //找到元素 } elseif(aa[f]+aa[l]>x) //两数和大数已知数时,移动尾游标 --l; else//两数和小于已知数时, 移动头游标 ++f; } if (f >= l) ...{ Console.WriteLine("数组s中没有和为"+ x.ToString() +"的俩元素"); } Console.ReadLine(); } //以下为快速排序 privatestaticvoid Swap(refint i, refint j) //swap two integer ...{ int t; t = i; i = j; j = t; } publicstaticvoid Sort(int[] list, int low, int high) ...{ if (high <= low) ...{ //only one element in array list //so it do not need sort return; } elseif (high == low +1) ...{ //means two elements in array list //so we just compare them if (list[low] > list[high]) ...{ //exchange them Swap(ref list[low], ref list[high]); return; } } //more than 3 elements in the arrary list //begin QuickSort myQuickSort(list, low, high); } publicstaticvoid myQuickSort(int[] list, int low, int high) ...{ if (low < high) ...{ int pivot = Partition(list, low, high); myQuickSort(list, low, pivot -1); myQuickSort(list, pivot +1, high); } } privatestaticint Partition(int[] list, int low, int high) ...{ //get the pivot of the arrary list int pivot; pivot = list[low]; while (low < high) ...{ while (low < high && list[high] >= pivot) ...{ high--; } if (low != high) ...{ Swap(ref list[low], ref list[high]); low++; } while (low < high && list[low] <= pivot) ...{ low++; } if (low != high) ...{ Swap(ref list[low], ref list[high]); high--; } } return low; } }