【问题标题】:Simple bubble sort c#简单冒泡排序 c#
【发布时间】:2013-01-23 22:47:39
【问题描述】:
int[] arr = {800,11,50,771,649,770,240, 9};

int temp = 0;

for (int write = 0; write < arr.Length; write++)
{
    for (int sort = 0; sort < arr.Length - 1; sort++)
    {
        if (arr[sort] > arr[sort + 1])
        {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }       
    }   
    Console.Write("{0} ", arr[write]);  
}

我想要做的只是用这个数组进行简单的冒泡排序。我想弄清楚为什么排序搞砸了。 例如,这里的数组是{800,11,50,771,649,770,240, 9}

下面是显示的内容:11, 50, 649, 9, 649, 770, 771, 800

我在想我可能会在比较中遗漏一些东西。

【问题讨论】:

  • 你的外循环从头到尾,应该是从头到尾!你的内部循环也应该限制为 write 的值。
  • 我希望这只是一个学习数组操作的练习?我想不出冒泡排序是“最佳”排序策略的任何应用程序。如果它只是用于演示/心理练习,那很好,但如果你使用的是真实世界的应用程序,也许你应该看看其他一些“排序”算法。
  • @Polity:我不认为这是正确的。正如答案所示,外循环是正确的。不过,关于内部循环,您是对的。

标签: c# arrays sorting bubble-sort


【解决方案1】:

不,您的算法有效,但您的 Write 操作在外循环中放错了位置。

int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

int temp = 0;

for (int write = 0; write < arr.Length; write++) {
    for (int sort = 0; sort < arr.Length - 1; sort++) {
        if (arr[sort] > arr[sort + 1]) {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }
    }
}

for (int i = 0; i < arr.Length; i++)
    Console.Write(arr[i] + " ");

Console.ReadKey();

【讨论】:

  • 致那些建议我写错地方的人,谢谢!这就是导致事情搞砸的原因。现在可以了
  • 你在哪里使用 write 在内循环?谢谢
  • @MindRoasterMir 第一个循环对数组进行排序,然后第二个 for 循环写入结果(倒数第二行)
【解决方案2】:

这个对我有用

public static int[] SortArray(int[] array)
{
    int length = array.Length;

    int temp = array[0];

    for (int i = 0; i < length; i++)
    {
        for (int j = i+1; j < length; j++)
        {
            if (array[i] > array[j])
            {
                temp = array[i];

                array[i] = array[j];

                array[j] = temp;
            }
        }
    }

    return array;        
}

【讨论】:

  • 有几乎相同的解决方案: int[] unsorted = new int[]{ 3,4,13,1,18,22,2,100,11 }; //冒泡排序 for (int i = 0; i
  • 不是Bubble sort。来自维基百科:“算法从数据集的开头开始。它比较前两个元素,如果第一个大于第二个,则交换它们。它继续对每对相邻元素执行此操作以数据集的结尾。 然后它再次从前两个元素开始,重复直到最后一遍没有发生交换。”
【解决方案3】:
public static void BubbleSort(int[] a)
    {

       for (int i = 1; i <= a.Length - 1; ++i)

            for (int j = 0; j < a.Length - i; ++j)

                if (a[j] > a[j + 1])


                    Swap(ref a[j], ref a[j + 1]);

    }

    public static void Swap(ref int x, ref int y)
    {
        int temp = x;
        x = y;
        y = temp;
    }

【讨论】:

  • 请不要只发布代码。解释一下您要向我们展示的内容。
  • 清晰且自记录的代码不需要 cmets。
【解决方案4】:
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

int temp = 0;

for (int write = 0; write < arr.Length; write++)
{
    for (int sort = 0; sort < arr.Length - 1 - write ; sort++)
    {
        if (arr[sort] > arr[sort + 1])
        {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }
    }
}

for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");

Console.ReadKey();

【讨论】:

    【解决方案5】:

    我看到有人将此示例用作工作申请测试的一部分。我给他的反馈是,当数组大部分排序时,它缺少从外部循环的逃逸。

    考虑在这种情况下会发生什么:

    int[] arr = {1,2,3,4,5,6,7,8};
    

    这里有一些更有意义的东西:

    int[] arr = {1,2,3,4,5,6,7,8};
    
    int temp = 0;
    int loopCount=0;
    bool doBreak=true;
    
    for (int write = 0; write < arr.Length; write++)
    {
        doBreak=true;
        for (int sort = 0; sort < arr.Length - 1; sort++)
        {
            if (arr[sort] > arr[sort + 1])
            {
                temp = arr[sort + 1];
                arr[sort + 1] = arr[sort];
                arr[sort] = temp;
                doBreak=false;
            }
            loopCount++;
        }
        if(doBreak){ break; /*early escape*/ }
    }
    
    Console.WriteLine(loopCount);
    for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");
    

    【讨论】:

    • 我同意您的反馈,但这不是从外部循环中逃脱的“传统”冒泡排序。
    【解决方案6】:

    我想在接受的答案中添加一些不同的东西: 迭代次数也可以减少,如下所示。

    int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
    
    int temp = 0;
    int arrLength = arr.Length;
    
    for (int write = 0; write < arr.Length - 1; write++, arrLength--)
    {
        for (int sort = 0; sort < arrLength - 1; sort++)
        {
            if (arr[sort] > arr[sort + 1])
            {
                temp = arr[sort + 1];
                arr[sort + 1] = arr[sort];
                arr[sort] = temp;
            }
        }
    }
    
    foreach (var item in arr)
    {
        Console.WriteLine(item);
    }
    

    【讨论】:

      【解决方案7】:

      你的Console.Write("{0} ", arr[write]); 太早了。您正在打印值排序仍在进行中。例如,您将 9 打印为数组中的索引 3,但在循环的下一次迭代中,9 已移动到索引 2 并且 240 已移动到索引 3...但是您're 外循环已经向前移动,所以它第二次打印649240 永远不会被打印。

      【讨论】:

      • 这不是真的,他正在打印最后写入的值。这确实意味着在修复之后,结果将按降序打印(尽管已排序)。
      • @Polity - He's printing out the last written value. - 我认为你误解了“冒泡排序”。他清楚地在算法完成排序之前将值输出到控制台。如果他只是想实现冒泡排序,那么上面的实际排序逻辑没有任何问题。 - en.wikipedia.org/wiki/Bubble_sort
      【解决方案8】:
      int[] array = new int[10] { 13, 2, 5, 8, 23, 90, 41, 4, 77, 61 };
      
      for (int i = 10; i > 0; i--)
      {
          for (int j = 0; j < 9; j++)
          {
              if (array[j] > array[j + 1])
              {
                  int temp = array[j];
                  array[j] = array[j + 1];
                  array[j + 1] = temp;
              }
          }
      }
      

      【讨论】:

        【解决方案9】:
            static bool BubbleSort(ref List<int> myList, int number)
            {
                if (number == 1)
                    return true;
                for (int i = 0; i < number; i++)
                {
                    if ((i + 1 < number) && (myList[i] > myList[i + 1]))
                    {
                        int temp = myList[i];
                        myList[i] = myList[i + 1];
                        myList[i + 1] = temp;
                    }
                    else
                        continue;
                }
                return BubbleSort(ref myList, number - 1);
            }
        

        【讨论】:

        • 也许也可以写一个简短的解释。
        【解决方案10】:

        只是另一个示例,但使用外部 WHILE 循环而不是 FOR:

        public static void Bubble()
            {
                int[] data = { 5, 4, 3, 2, 1 };
                bool newLoopNeeded = false;
                int temp;
                int loop = 0;
        
                while (!newLoopNeeded)
                {
                    newLoopNeeded = true;
                    for (int i = 0; i < data.Length - 1; i++)
                    {
                        if (data[i + 1] < data[i])
                        {
                            temp = data[i];
                            data[i] = data[i + 1];
                            data[i + 1] = temp;
                            newLoopNeeded = false;
                        }
                        loop++;
                    }
                }
            }
        

        【讨论】:

        • 这个 while 循环示例比上面的默认 BubbleSort 和早期转义 BubbleSort 算法都慢...
        【解决方案11】:
        public static int[] BubbleSort(int[] arr)
        {
           int length = arr.Length();
        
           while (length > 0)
           {
              int newLength = 0;
              for (int i = 1; i < length; i++)
              {
                 if (arr[i - 1] > arr[i])
                 {
                    Swap(ref arr[i - 1], ref arr[i]); 
                    newLength = i;   
                 }   
              }
              length = newLength;
           }
        }
        
        public static void Swap(ref int x, ref int y)
        {
           int temp = y;
           y = x;
           x = temp;
        }
        

        【讨论】:

          【解决方案12】:

          带排序方向的冒泡排序 -

          using System;
          
          public class Program
          {
              public static void Main(string[] args)
              {
                  var input = new[] { 800, 11, 50, 771, 649, 770, 240, 9 };
          
                  BubbleSort(input);
          
                  Array.ForEach(input, Console.WriteLine);
          
                  Console.ReadKey();
              }
          
              public enum Direction
              {
                  Ascending = 0,
                  Descending
              }
          
              public static void BubbleSort(int[] input, Direction direction = Direction.Ascending)
              {
                  bool swapped;
                  var length = input.Length;
          
                  do
                  {
                      swapped = false;
                      for (var index = 0; index < length - 1; index++)
                      {
                          var needSwap = direction == Direction.Ascending ? input[index] > input[index + 1] : input[index] < input[index + 1];
          
                          if (needSwap)
                          {
                              var temp = input[index];
                              input[index] = input[index + 1];
                              input[index + 1] = temp;
                              swapped = true;
                          }
                      }
                  } while (swapped);
              }
          }
          

          【讨论】:

            【解决方案13】:

            这是我用递归方法写的:

                public static int[] BubbleSort(int[] input)
                {
                    bool isSorted = true;
                    for (int i = 0; i < input.Length; i++)
                    {
                        if (i != input.Length - 1 && input[i] > input[i + 1])
                        {
                            isSorted = false;
                            int temp = input[i];
                            input[i] = input[i + 1];
                            input[i + 1] = temp;
                        }
                    }
                    return isSorted ? input : BubbleSort(input);
                }
            

            【讨论】:

              【解决方案14】:

              它以更优雅的方式做同样的事情。

              var arrayValues = new[] { 99, 12, 11, 300, 400, 10, 9, 3, 6, 5, 7, 8};
              for (var mainLoop = 0; mainLoop < arrayValues.Length; mainLoop++)
              {
                 for (var innerLoop = mainLoop + 1; innerLoop < arrayValues.Length; innerLoop++)
                 {
                     if (arrayValues[mainLoop] <= arrayValues[innerLoop])
                     {
                       continue;
                     }
              
                     var temp = arrayValues[mainLoop];
                     arrayValues[mainLoop] = arrayValues[innerLoop];
                     arrayValues[innerLoop] = temp;
                }
              }
              

              【讨论】:

                【解决方案15】:

                所以我将我的作为递归函数(不需要嵌套循环),也许有人可以评论这是否效率低下(与其他解决方案相比)。

                    public static int[] BubbleSort(int[] arrayOfValues)
                    {
                        var swapOccurred = false;
                        
                        for (var i = 0; i < arrayOfValues.Length; i++)
                        {
                            if (i == arrayOfValues.Length - 1)
                                continue;
                
                            if (arrayOfValues[i] > arrayOfValues[i + 1])
                            {
                                //swap values
                                var current = arrayOfValues[i];
                                var next = arrayOfValues[i + 1];
                                
                                arrayOfValues[i] = next;
                                arrayOfValues[i + 1] = current;
                
                                swapOccurred = true;
                            }
                        }
                
                        if (swapOccurred)
                        {
                            // keep going until no further swaps are required:
                            BubbleSort(arrayOfValues);
                        }
                
                        return arrayOfValues;
                    }
                

                【讨论】:

                  【解决方案16】:
                     using System; 
                   using System.Collections.Generic; 
                   using System.Linq;  
                  using System.Text; 
                   using System.Threading.Tasks;
                  
                  namespace Practice {
                      class Program
                      {
                          static void Main(string[] args)
                          {
                              Console.WriteLine("Enter the size");
                              int n = Convert.ToInt32(Console.ReadLine());
                              int[] mynum = new int[n];
                              Console.WriteLine("Enter the Numbers");
                              for (int p = 0; p < n;p++ )
                              {
                                  mynum[p] = Convert.ToInt32(Console.ReadLine());
                  
                              }
                              Console.WriteLine("The number are");
                                  foreach(int p in mynum)
                                  {
                                      Console.WriteLine(p);
                                  }
                                  for (int i = 0; i < n;i++ )
                                  {
                                      for(int j=i+1;j<n;j++)
                                      {
                                          if(mynum[i]>mynum[j])
                                          {
                                              int x = mynum[j];
                                              mynum[j] = mynum[i];
                                              mynum[i] = x;
                                          }
                                      }
                                  }
                                  Console.WriteLine("Sortrd data is-");
                              foreach(int p in mynum)
                              {
                                  Console.WriteLine(p);
                              }
                                      Console.ReadLine();
                          }
                      } }
                  

                  【讨论】:

                  • 它错了 - 你在这里显示选择排序。您正在将第一个元素 I = 0 与 j = I+1 的每个元素进行比较,这是选择排序而不是冒泡排序。在冒泡排序中,每次通过的第一个元素 j = 与 j + 1 进行比较,如果不是按顺序进行比较被交换,这将在 i 上的每一次传递中完成。请检查你的 for 循环和 matten 的第一个答案
                  【解决方案17】:
                  int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
                  for (int i = 0; i < arr.Length; i++)
                  {
                      for (int j = i; j < arr.Length ; j++)
                      {
                          if (arr[j] < arr[i])
                          {
                              int temp = arr[i];
                              arr[i] = arr[j];
                              arr[j] = temp;
                          }
                      }
                  }
                  Console.ReadLine();
                  

                  【讨论】:

                  • 这是错误的,您显示的上述代码是选择排序-不是冒泡排序..在冒泡排序中,您移动的是比较相邻元素..请更新它。 for (int i = 0; i arr[j+i]) { int温度 = arr[j+1]; arr[j+1] = arr[j]; arr[j] = 温度; } } }
                  【解决方案18】:
                      public void BubbleSortNum()
                      {
                          int[] a = {10,5,30,25,40,20};
                          int length = a.Length;
                          int temp = 0; 
                          for (int i = 0; i <length; i++)
                          {               
                              for(int j=i;j<length; j++)
                              {
                                  if (a[i]>a[j])
                                  {
                                      temp = a[j];
                                      a[j] = a[i];
                                      a[i] = temp;
                                  }     
                              }
                             Console.WriteLine(a[i]);
                          }       
                       }
                  

                  【讨论】:

                    猜你喜欢
                    • 2015-06-22
                    • 2014-03-26
                    • 2018-11-13
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-02-25
                    • 2017-06-21
                    • 2012-07-19
                    相关资源
                    最近更新 更多