.NET 冒泡排序 查询出相等的值

    技术2022-05-19  27


     /// <summary>  /// 冒泡排序  /// </summary>   public  static void BubbleSort()    {    int[] myArray = new int[] { 10, 8,3,8,13,56,88,56,10,5, 6, 7, 4, 6, 9 };    for (int k = 0; k < myArray.Length; k++)    Console.Write("{0},",myArray[k]);    Console.WriteLine();    // 取长度最长的词组 -- 冒泡法    for (int j = 1; j < myArray.Length; j++)    {     for (int i = 0; i < myArray.Length-1; i++)    {    // 如果 myArray[i] > myArray[i+1] ,则 myArray[i] 下沉一位    if (myArray[i] > myArray[i + 1])    {    int temp = myArray[i];    myArray[i] = myArray[i + 1];    myArray[i + 1] = temp;    }    }    }    for (int k = 0; k < myArray.Length; k++)    Console.Write("{0},", myArray[k]);       Console.WriteLine();

                   //查询出相等的数    IList<int> Leaqul = new List<int>();    for (int i = 0; i < myArray.Length; i++)    {     for (int j = i + 1; j < myArray.Length; j++)     {      if (myArray[i] == myArray[j])      {       Leaqul.Add(myArray[i]);      }     }    }

              for (int k = 0; k < Leaqul.Count; k++)     Console.Write("{0},", Leaqul[k]);    Console.ReadKey();

        }

     


     

         考虑时间复杂度,需要对其稍微改动;

        /// <summary>    /// 冒泡排序    /// </summary>    public static void BubbleSort()    {

         int[] myArray = new int[] { 10, 8, 3, 8, 13, 56, 88, 56, 10, 5, 6, 7, 4, 6, 9 };     //查询出相等的数     IList<int> Leaqul = new List<int>();     for (int i = 0; i < myArray.Length; i++)     {      for (int j = i + 1; j < myArray.Length; j++)      {       if (myArray[i] == myArray[j])       {        Leaqul.Add(myArray[i]);       }      }     }

         for (int k = 0; k < Leaqul.Count; k++)      Console.Write("{0},", Leaqul[k]);      Console.WriteLine();      

            for (int k = 0; k < myArray.Length; k++)     Console.Write("{0},", myArray[k]);     Console.WriteLine();     // 取长度最长的词组 -- 冒泡法     for (int j = 0; j < myArray.Length; j++)     {      for (int i = j+1; i < myArray.Length; i++)      {       // 如果 myArray[i] > myArray[i+1] ,则 myArray[i] 下沉一位       if (myArray[j] > myArray[i])       {        int temp = myArray[j];        myArray[j] = myArray[i];        myArray[i] = temp;       }      }     }     for (int k = 0; k < myArray.Length; k++)      Console.Write("{0},", myArray[k]);     Console.WriteLine();     Console.ReadKey(); }


    最新回复(0)